๐Ÿ
๐Ÿ Intermediate Python ยท PY-201 ยท Session 2 of 6

Working with Files

Real programs read and write files โ€” save data, load it back, process a document. It's simpler than it looks, and the `with` statement makes it safe.

โฑ 8 min read๐Ÿ“… Updated 2026-07-28๐Ÿ“Š Tables, charts & examples

So far your programs have started empty and forgotten everything when they end. Real programs persist: they save results to a file and load them back later, or read a document to process it. Files are how a program remembers - and Python makes them straightforward, especially with the with statement that handles the fiddly cleanup for you.

Read and write with open()

You open a file, read or write, and close it. The with statement does the closing automatically - always use it.

# write
with open("notes.txt", "w") as f:
    f.write("first line\n")
    f.write("second line\n")

# read it back
with open("notes.txt") as f:
    text = f.read()          # whole file as one string

# read line by line (memory-friendly for big files)
with open("notes.txt") as f:
    for line in f:
        print(line.strip())
๐ŸŽฏ
Always use with open(...) as f:. It guarantees the file is closed properly even if something goes wrong in the middle - no leaked file handles, no half-written files. The mode matters: "r" reads (the default), "w" writes (and erases any existing content!), "a" appends to the end. Mixing these up - opening in "w" when you meant "a" - is a classic way to accidentally wipe a file, so read the mode twice when writing.

Simple data formats

To save structured data (not just plain text), use a format. JSON is the everyday choice - it turns Python dicts and lists into text and back.

import json

data = {"name": "Ada", "scores": [90, 85]}

with open("data.json", "w") as f:
    json.dump(data, f)        # dict -> file

with open("data.json") as f:
    loaded = json.load(f)     # file -> dict
Mode / toolUse it to
open(path, "r")Read an existing file (default)
open(path, "w")Write - CAUTION: erases existing content
open(path, "a")Append to the end, keeping what's there
json.dump / loadSave & load dicts/lists as JSON

For tabular data there's also the csv module. The pattern is always the same: open with 'with', use the right tool to convert between text and Python objects.

Make programs remember

  • with open(...) as f: - the safe way to read/write; it always closes the file.
  • Modes: "r" read, "w" write (erases!), "a" append.
  • Iterate a file line by line for big files instead of read().
  • json.dump/load saves and restores structured data (dicts, lists).

๐ŸŽฏ Key takeaways

  • Files are how a program persists - saving results and loading them back.
  • Always use 'with open(...) as f:' - it closes the file safely even on errors.
  • Modes matter: 'r' read, 'w' write (erases existing content!), 'a' append.
  • Use json.dump/load to save and restore structured data like dicts and lists.

Frequently asked

Why is the 'with' statement better than just calling open() and close()?

Because 'with' guarantees the file gets closed no matter what happens - and forgetting to close files, or failing to close them when an error interrupts your code, causes real problems. If you open a file, then an exception is raised before your close() line runs, the file stays open: on some systems its data may not be fully written to disk, and open handles are a limited resource that can leak. The 'with' statement (a 'context manager') handles this automatically - the moment the indented block ends, whether normally or because of an error, the file is properly closed and flushed. It's less code and it's safe, which is why it's the standard, recommended way to work with files in Python. Get in the habit and you'll never leak a file handle.

What's the difference between 'w' and 'a' mode, and how do I avoid losing data?

'w' (write) mode opens a file for writing and immediately erases any existing content - you start from a blank file. 'a' (append) mode opens for writing but keeps what's already there and adds new content to the end. The danger is using 'w' when you meant to add to a file: opening an important file in 'w' mode wipes it instantly, before you write a single thing. To avoid losing data: use 'a' when you want to add to existing content (like a log), reserve 'w' for when you genuinely want to replace the file's contents, and when in doubt, read the file first or write to a new filename. Reading doesn't risk your data (use 'r'), so the caution is specifically around 'w'. A good habit is to double-check the mode every time you open a file for writing.

Session 2 of 6 complete

Next up: Errors & Exceptions

Continue to Session 3 โ†’

Related lessons

More in this course

Course home → · Browse all courses →