Applied PythonLesson 16 of 1914 min
Reading and Writing Files
Persist data to disk with `with open(...)`, and handle text line by line.
By the end you will be able to
- Open files safely with a with block
- Choose between the r, w, and a modes
- Read a file line by line and write results back out
open() gives you a file object. Always use it in a with block: the file is closed automatically when the block ends, even if an error is raised partway through.
The second argument is the mode:
"r"— read (the default); errors if the file is missing"w"— write; creates or truncates, wiping any existing content"a"— append; adds to the end, keeping what is there
First line
Second line
Third line
---
34 characters
— expected output; press Run to execute it yourselfReading line by line
For anything but a small file, loop over the file object directly. It yields one line at a time and never loads the whole thing into memory. Each line keeps its trailing newline, so .strip() is usually the next step.
ada 88
bob 92
cleo 79
Average: 86.3
— expected output; press Run to execute it yourselfMissing files
Reading a file that does not exist raises FileNotFoundError. Catch it rather than letting the program die.
'<no such file>'
— expected output; press Run to execute it yourselfExercise
Write save_and_count(path, lines) that writes each string in lines to path as its own line, then reopens the file and returns the number of lines it contains.
Press Run to execute this code.