FlashKeepers

Python · Python · College and University

Python: File I/O and Error Handling

Python file reading/writing and try/except exception handling patterns explained with a short example each.

About this set

36 basic cards for Python Python. Set 2 of 11 in Python. It opens with "How do you open a file named 'data.txt' in read mode?" and "What does 'r' mode do when opening a file?". More College and University decks are listed below.

36 cards · basic cards · AI-written, checked twice. Edit anything.

Study this set free Look inside first Get FlashKeepers for iPhone

Opens in your browser, no account. Get the iPhone and iPad app · Android app

How do you open a file named 'data.txt' in read mode?
Show answeropen('data.txt', 'r')
What does 'r' mode do when opening a file?
Show answerOpens the file for reading. The file must exist or FileNotFoundError is raised.
What does 'w' mode do when opening a file?
Show answerOpens the file for writing. Creates the file if it does not exist, or truncates it if it does.
What does 'a' mode do when opening a file?
Show answerOpens the file for appending. New data is written at the end without truncating existing content.
Why use 'with open(filename) as f:' instead of open() alone?
Show answerThe 'with' statement (context manager) automatically closes the file when the block exits, even if an error occurs.
What does the read() method return?
Show answerReturns the entire file contents as a single string.
What does readline() return?
Show answerReturns one line from the file as a string, including the newline character at the end.
What does readlines() return?
Show answerReturns a list of strings, one string per line in the file, each including the newline character.
How do you iterate over lines in a file one at a time?
Show answerUse 'for line in file_object:' to loop through each line without loading the entire file into memory.
What does the write() method do?
Show answerWrites a string to the file. Returns the number of characters written.
What does writelines() do?
Show answerWrites a sequence (list) of strings to the file. Does not add newlines between items.
What is the purpose of a try/except block?
Show answertry contains code that might raise an exception; except handles the error if it occurs.
Why catch specific exceptions instead of using bare 'except:'?
Show answerSpecific exceptions allow you to handle different errors differently and avoid catching unexpected errors.
What exception is raised when open() cannot find a file?
Show answerFileNotFoundError (a subclass of OSError).
Can you have multiple except blocks for one try block?
Show answerYes, each except clause can catch different exception types and handle them separately.

21 more cards in the app

Study this set free