FlashKeepers

Python · Python

Python: File I/O and Error Handling

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

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

Study this set free Look inside first Get FlashKeepers for iPhone
How do you open a file named 'data.txt' in read mode?
open('data.txt', 'r')
What does 'r' mode do when opening a file?
Opens the file for reading. The file must exist or FileNotFoundError is raised.
What does 'w' mode do when opening a file?
Opens 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?
Opens 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?
The 'with' statement (context manager) automatically closes the file when the block exits, even if an error occurs.
What does the read() method return?
Returns the entire file contents as a single string.
What does readline() return?
Returns one line from the file as a string, including the newline character at the end.
What does readlines() return?
Returns 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?
Use 'for line in file_object:' to loop through each line without loading the entire file into memory.
What does the write() method do?
Writes a string to the file. Returns the number of characters written.
What does writelines() do?
Writes a sequence (list) of strings to the file. Does not add newlines between items.
What is the purpose of a try/except block?
try contains code that might raise an exception; except handles the error if it occurs.
Why catch specific exceptions instead of using bare 'except:'?
Specific exceptions allow you to handle different errors differently and avoid catching unexpected errors.
What exception is raised when open() cannot find a file?
FileNotFoundError (a subclass of OSError).
Can you have multiple except blocks for one try block?
Yes, each except clause can catch different exception types and handle them separately.

21 more cards in the app