File Handling
Data That Survives
Every program you've written so far forgets everything when it ends. Variables live in memory — the moment the program stops, they're gone.
Files change this. Writing data to a file means it persists. Reading a file means your program can work with data that was prepared elsewhere — by another program, another person, or a previous run of your own code.
This lesson uses Python's standard file API, running in the browser's in-memory filesystem. The syntax is identical to what you'd write on a real machine.
Writing a File
Three things to understand here:
open("notes.txt", "w") — Opens a file called notes.txt in write mode. "w" creates the file if it doesn't exist, or overwrites it if it does.
with ... as f: — The with statement is a context manager. It opens the file, gives you access through f, and automatically closes the file when the block ends — whether or not an error occurred. Always use with for files. Forgetting to close a file is a classic source of subtle bugs.
f.write() — Writes text to the file. Notice \n — write() doesn't add newlines automatically the way print() does. You must include them explicitly.
Reading a File
"r" opens in read mode. f.read() reads the entire file as one string. The newlines are preserved in the string.
Reading Line by Line
For large files, reading the entire content at once is wasteful. Reading line by line is more efficient and often more natural:
Looping directly over the file object reads one line at a time. strip() removes the trailing newline from each line — almost always what you want.
Alternatively, readlines() reads all lines at once into a list:
Appending to a File
"w" overwrites. "a" (append mode) adds to the end without touching existing content:
The first open creates the file with Entry 1. The second open in append mode adds to it — Entry 1 is untouched. This is how log files, journals, and audit trails are built.
Handling Missing Files
Trying to read a file that doesn't exist raises FileNotFoundError:
This is the standard pattern: try to read the file, handle the case where it doesn't yet exist. You'll use this whenever a program needs to load saved state at startup.
Working With CSV Data
CSV (Comma-Separated Values) is one of the most common data formats. Python's csv module handles it cleanly:
csv.writer handles quoting and escaping automatically — you give it plain Python lists and it produces correct CSV. csv.reader parses the file and gives you each row as a list of strings.
For named column access, DictReader is even more convenient:
DictReader uses the first row as keys and gives you each subsequent row as a dictionary. Accessing person["name"] is far clearer than row[0].
File Modes at a Glance
| Mode | Meaning |
|---|---|
"r" | Read (default). File must exist. |
"w" | Write. Creates or overwrites. |
"a" | Append. Creates if absent, adds to end if present. |
"r+" | Read and write. File must exist. |
What You Have Learned
Files are how programs persist data and communicate with the world outside memory.
The key ideas:
open(filename, mode)opens a file; always use it inside awithblock"r"reads,"w"writes (overwrites),"a"appendsf.read()reads the whole file;f.readlines()reads into a list; looping overfreads line by linestrip()removes trailing newlines when reading linesFileNotFoundErroris the exception to catch when a file may not exist- Python's
csvmodule handles reading and writing CSV cleanly csv.DictReadergives you each row as a dictionary — the most readable way to work with structured CSV data
In the next lesson, you'll explore Python's standard library — the large collection of ready-made modules that come with every Python installation.