Lesson 18 of 26 · about 15 min
Reading and writing files
Files let data outlive your program. Open a file, read it line by line or write to it, and Python closes it for you with a with block.
🧭 What you need first: Dictionaries and sets
Everything you’ve stored so far lives in variables, and variables are like writing on a whiteboard: the moment the program ends, it’s wiped.
Files are the notebook in the drawer. Write something down, close the notebook, come back next week, and it’s still there. Your photos, documents, saved games and settings are all files.
Using a file is like using a notebook: open it, read or write, and close it when you’re done. Python’s with block closes it for you automatically, even if something goes wrong halfway.
Another way: a diary
“r” is reading your diary. “a” (append) is adding today’s entry at the end. “w” (write) is tearing out every page and starting fresh. Be careful with “w”!
Another way: a library book
You check the book out (open), read it, and return it (close). If you forget to return it, others can’t use it. The with block is a librarian who takes the book back automatically.
Read a real file
This program can open pets.txt. Run it, then try f.read() instead of the loop, or print repr(line) to see the hidden newline at the end of each line.
📁 Files your program can open: pets.txt
The real words
- A file is named data stored on disk. It persists: it survives after the program ends.
open(name, mode)opens a file. Modes:"r"read (the default),"w"write (erases existing content),"a"append.- with open(…) as f: is the standard way. The file is closed automatically when the block ends.
- Reading:
for line in f:reads one line at a time (good for big files).f.read()gives the whole file as one string;f.readlines()gives a list of lines.- Each line ends with
"\n"(a newline character).line.strip()removes it.
- Writing:
f.write(text)doesn’t add a newline for you; add"\n"yourself. - CSV (“comma-separated values”) is a simple, very common format:
name,scoreper line. Reading it is parsing: split each line on commas and convert the pieces to the right types. - If the file doesn’t exist,
openraisesFileNotFoundError. You’ll handle that in the next lesson.
Grade report from a file
Read scores.csv (name,score per line, with a header line first). Work out the class average, then write it to report.txt as 'Average: 84.0'.
📁 Files your program can open: scores.csv
Keep a log
log.txt already has one line. Append two more lines ('lunch' and 'nap') without erasing it, then read the file back and set line_count to the number of lines.
📁 Files your program can open: log.txt
What happens to an existing file when you open it with mode "w"?
Got it?
Finish the lesson to color it in on your map and collect its concept cards.
Did this lesson click?