Module 11: Study Guide
Review key concepts from File Handling
Key Terms
File object: The Python object returned by
open() that provides methods to read or write file data.File mode: A string like "r", "w", "a" that tells Python how to open the file.
Context manager: An object used with the
with statement that automatically manages setup and cleanup (like opening and closing files).CSV: Comma-Separated Values - a plain text format for tabular data where commas separate values in each row.
Newline character: The invisible
\n character that marks the end of a line in a text file.Lesson 1: Reading Files
open(filename, "r")opens a file for readingread()- entire file as one stringreadline()- one line at a timereadlines()- all lines as a list- Iterating directly:
for line in file:(most efficient) - Use
strip()to remove trailing newline characters - FileNotFoundError occurs if the file does not exist
Lesson 2: Writing Files
"w"mode creates or overwrites a file (erases existing content)"a"mode appends to the end (keeps existing content)write()does NOT add newlines - you must include\nwritelines()writes a list of strings"x"mode creates a file but raises an error if it already exists
Lesson 3: The with Statement
with open() as file:automatically closes the file when the block ends- Files are closed even if an error occurs inside the block
- Variables created inside the block remain available after it ends
- You can nest
withstatements for multiple files - The
withstatement is the recommended approach for all file operations
Lesson 4: CSV Data
csv.readerreads rows as lists (access by index)csv.DictReaderreads rows as dictionaries (access by column name)csv.writerwrites lists withwriterow()andwriterows()csv.DictWriterwrites dictionaries withwriteheader()andwriterows()- Use
newline=""inopen()when writing CSV files - CSV values are always strings - convert with
int()orfloat()as needed - Use
next(reader)to skip the header row withcsv.reader
Review Questions
1. What is the difference between "w" and "a" file modes?
2. Why is the with statement preferred over manual open()/close()?
3. What is the difference between read(), readline(), and readlines()?
4. Why do we need newline="" when writing CSV files?
5. What is the advantage of DictReader over csv.reader?
6. What happens if you forget to close a file?
Common Mistakes to Avoid
- Forgetting to add
\nwhen writing lines - Using
"w"mode when you meant to append (data loss!) - Forgetting to convert CSV values from strings to numbers
- Not using
strip()when reading lines (extra whitespace in output) - Forgetting
newline=""when writing CSV on Windows - Trying to read a file that does not exist without handling the error
- Not using the
withstatement (risk of unclosed files)