49
File Handling
File Handling: Making Data Persistent
What might confuse you right now
"I have data in variables. Why write to a file?"
Memory gets wiped when the program ends. Files are how you save and share data long-term.
One-line definition
File handling is reading, writing, and appending data to disk using different modes.
Real-life analogy
Variables are like whiteboard notes -- gone when the power's off. Files are like notebooks -- they stick around.
Minimal runnable example
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("Hello Python\n")
with open("demo.txt", "r", encoding="utf-8") as f:
print(f.read())
Mode selection
r: readw: overwritea: append
Quick quiz (5 min)
- Write three lines of text, then read them back.
- Append one more line using
amode. - Count the total number of lines in the file.
Quiz answer guidelines & grading criteria
- Answer direction: working code that covers core conditions and edge inputs from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Transfer task (homework)
Build a "log summarizer": read log files, output a summary file.
Acceptance criteria
You can independently:
- Read and write files using
with open() - Choose the right
r/w/amode - Handle encoding issues
Common errors & debugging steps (beginner edition)
- Can't understand the error: read the last line for the error type (e.g.,
TypeError,NameError), then trace back to the relevant code line. - Not sure about a variable's value: temporarily add
print(variable, type(variable))at key points to verify data matches expectations. - Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.
Common misconceptions
- Misconception: Forgetting to specify encoding.
- Reality: Always explicitly use
utf-8for text files.