Skip to content
CodeNest

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
Python
Output
First line
Second line
Third line

---
34 characters
— expected output; press Run to execute it yourself

Reading 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.

Python
Output
ada    88
bob    92
cleo   79
Average: 86.3
— expected output; press Run to execute it yourself

Missing files

Reading a file that does not exist raises FileNotFoundError. Catch it rather than letting the program die.

Python
Output
'<no such file>'
— expected output; press Run to execute it yourself

Exercise

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.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.What is the advantage of with open(...) as f: over a plain open()?
  2. 2.What happens to an existing file opened with mode "w"?