Day 26 · ~13m

Reading Files

open(), read(), readlines(), the with statement, and file modes — your first step into real-world data.

🧑‍💻

Wait, we can actually READ my CSV files? Like, the ones I export from our CRM?

👩‍🏫

Yes. This is the day everything changes. Up until now, every piece of data in your programs has been typed directly into the code. Lists you wrote by hand. Dictionaries you defined. Starting today, your programs reach out into the real world and pull data from files.

Python makes this straightforward with the built-in open() function:

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

open() takes a filename and a mode. "r" means read mode (the default). .read() grabs the entire file as one big string. And .close() releases the file when you're done.

🧑‍💻

What happens if I forget to close it?

👩‍🏫

The file stays locked — other programs might not be able to use it, and your program leaks resources. This is such a common mistake that Python has a better pattern — the with statement:

with open("data.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed here, even if an error occurs

The with block guarantees the file gets closed when the block ends. Always use with. No exceptions. It's like putting on a seatbelt — there's no scenario where skipping it is a good idea.

🧑‍💻

.read() gives me the whole file as one string. But what if the file is huge — like a year's worth of transaction logs?

👩‍🏫

Two options. .readlines() returns a list where each element is one line:

with open("students.txt", "r") as file:
    lines = file.readlines()
    print(lines)  # ["Alice\n", "Bob\n", "Charlie\n"]

Or iterate directly over the file — this is the most Pythonic way and handles files of any size:

with open("students.txt", "r") as file:
    for line in file:
        print(line.strip())  # .strip() removes the trailing newline

Iterating reads one line at a time, so it doesn't load the whole file into memory. For a 10GB log file, this is the difference between your program working and your program crashing.

🧑‍💻

What are the different file modes? You mentioned "r" for reading.

👩‍🏫

The ones you'll use most:

ModeDescription
"r"Read (default) — file must exist
"w"Write — creates file or overwrites existing
"a"Append — creates file or adds to the end
"r+"Read and write

Focus on "r" for today. We'll cover writing in a couple of days.

🧑‍💻

What if the file doesn't exist?

👩‍🏫

Python raises a FileNotFoundError:

with open("missing.txt", "r") as file:
    content = file.read()
# FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

In production code you'd catch this with try/except. For now, just make sure the filename is right.

🧑‍💻

How does this work in the zuzu sandbox?

👩‍🏫

The zuzu SDK provides zuzu.files.read(filename) which returns file content as a string. Same concept, sandbox-friendly:

import zuzu

content = zuzu.files.read("students.txt")
lines = content.strip().split("\n")
for line in lines:
    print(line)

The processing is identical — you get a string and work with it. Split on newlines, strip whitespace, parse the data. Everything you learned about strings and lists in Weeks 1-3 was preparation for this moment.

Let's read some data.

Practice your skills

Sign up to write and run code in this lesson.

Already have an account? Sign in