Day 28 · ~13m

Writing Files

Writing to files — write mode vs append, writing structured data, and real-world file output patterns.

🧑‍💻

We've been reading files and processing data. But what about the other direction — creating output? I want to generate reports, not just analyze them.

👩‍🏫

Now you're thinking like someone who automates things. Same open() function, different mode. Use "w" for write mode:

with open("output.txt", "w") as file:
    file.write("Hello, world!\n")
    file.write("Second line.\n")

Two critical things about write mode: it creates the file if it doesn't exist, and it overwrites the file completely if it does. Every time you open with "w", you start with a blank slate.

🧑‍💻

That sounds dangerous. What if I accidentally overwrite something important?

👩‍🏫

Good instinct. That's why append mode exists — "a":

# First run — creates the file
with open("log.txt", "a") as file:
    file.write("Event 1: Started\n")

# Second run — adds to the file
with open("log.txt", "a") as file:
    file.write("Event 2: Completed\n")

# log.txt now contains both lines

Append mode keeps everything that's already there and tacks new content on the end. Perfect for log files, running totals, or any time you're building up data over time.

ModeFile existsFile doesn't exist
"w"OverwritesCreates
"a"AppendsCreates
🧑‍💻

I notice .write() doesn't add newlines automatically. That tripped me up.

👩‍🏫

Yep — unlike print(), .write() writes exactly what you give it. Nothing more. If you want a newline, include "\n" yourself.

For writing multiple lines, build the full string first and write once:

data = ["Alice,92", "Bob,85", "Charlie,67"]
output = "\n".join(data) + "\n"
with open("students.txt", "w") as file:
    file.write(output)

The "\n".join() pattern — you've been using it since Week 2 with strings. Now it's building file output.

🧑‍💻

How do I write a CSV file? Like, something I could open in Excel?

👩‍🏫

Build each line as a comma-separated string, then write them all:

students = [
    {"name": "Alice", "score": 92, "grade": "A"},
    {"name": "Bob", "score": 85, "grade": "B"},
]

header = "name,score,grade"
lines = [header]
for s in students:
    lines.append(f"{s['name']},{s['score']},{s['grade']}")

with open("report.csv", "w") as file:
    file.write("\n".join(lines) + "\n")

This pattern — build a list of strings, join them, write once — is how you produce any output file. And yes, you could email that CSV to your team and they'd open it in Excel like nothing happened.

🧑‍💻

What about a plain text report? Like a summary you'd send to your manager?

👩‍🏫

Same idea, formatted text instead of raw data:

report_lines = []
report_lines.append("=== Student Report ===")
report_lines.append(f"Total Students: {len(students)}")
report_lines.append(f"Average Score: {avg}")
report_lines.append("")
for s in students:
    report_lines.append(f"  {s['name']}: {s['score']} ({s['grade']})")

with open("report.txt", "w") as file:
    file.write("\n".join(report_lines) + "\n")
🧑‍💻

I just realized something. I can read a file, process the data with everything I learned in Weeks 1-3, and write the results to a new file. I just automated something that used to take me an hour. This is insane.

👩‍🏫

That's the pipeline: file in, process, file out. And in the zuzu sandbox, use zuzu.files.write(filename, content):

import zuzu
zuzu.files.write("report.txt", "\n".join(report_lines))

Same pattern. Build your content, write it in one call.

Let's build a real report.

Practice your skills

Sign up to write and run code in this lesson.

Already have an account? Sign in