Reading files
🌍 In real life. When you read a story book, you keep a bookmark in it: you read a page, the bookmark moves on, and next time you carry on from the bookmark instead of the start. When you're done, you close the book and put it back on the shelf.
Reading a file in Python works the same way: open it, read from where the bookmark is, and close it when you're done.
The idea in one sentence: with open(name) as f: opens a file for reading and closes it automatically when the block ends, and every read continues from a cursor where the last read stopped.
Its words:
- file object: what
opengives back,f, used to read the file with ... as f:: opens the file, and closes it when the indented block ends, even after an error- cursor: the bookmark: where the next read starts
f.read(): the rest of the file as one string;f.readline(): just the next line;for line in f:one line at a time
Step by step, for the drawer below:
- The file holds three lines, and the cursor is at the start.
f.readline()reads "Ana\n", and the cursor moves to the next line.f.read()reads everything from the cursor to the end: "Bo\nCy\n".
with open("notes.txt") as f:
text = f.read()
print(text)A for loop over a file gives you one line at a time. Each line still ends with its \n, so .strip() it before using it:
with open("notes.txt") as f:
for number, line in enumerate(f, start=1):
print(number, line.strip())f.readlines() gives all the lines as a list. Opening a file that isn't there is a FileNotFoundError:
with open("nope.txt") as f:
print(f.read())Why with? An open file holds on to something the operating system lends you; forgetting to close it can lose data or leave the file locked. with closes it for you at the end of the block, however the block ends, so you never have to remember.
What it costs. f.read() loads the whole file into memory at once: fine for notes, a problem for a file of several gigabytes. for line in f: holds only one line at a time, so it works for files of any size.
Mistakes and edge cases.
- A missing file.
open("nope.txt")stops with aFileNotFoundError: ... No such file or directory: 'nope.txt'(above). - Forgetting the \n. Each line still ends with
\n, so printing it adds a blank line;.strip()it. - Reading twice. After
f.read(), the cursor is at the end, so a secondf.read()gives"". - Using f after the with block. The file is closed:
ValueError: I/O operation on closed file.
Quiz
What does this print?
with open("a.txt", "w") as f: f.write("one\ntwo\nthree\n") with open("a.txt") as f: print(len(f.readlines()))What does this print?
with open("a.txt", "w") as f: f.write("red\ngreen\nblue\n") with open("a.txt") as f: f.readline() print(f.readline().strip())What does
with open(...) as f:do for you?- Closes the file when the indented block ends
- Makes the file if it doesn't exist
- Reads the whole file into f
What does this print?
print(repr("Ana\n".strip()))Which line has a mistake?
with open("a.txt", "w") as f: f.write("hi") with open("a.txt") as f: pass print(f.read())
Coding tasks
Write
count_lines(filename)that returns how many lines the file has. Try it onpoem.txtandshort.txt.Each line of the file is a whole number. Write
total_score(filename)that returns their sum.Write
longest_line(filename)that returns the file's longest line, without its\n.