Advanced

Files and Context Managers

Read and write files safely using the with statement and context managers.

What you will see

Ada 30

About 2 min of reading

Try It

Read, write, and load JSON files using the `with` statement. Each step modifies files in your working folder.

1

Create a text file and read it back

with open("notes.txt", "w", encoding="utf-8") as f: f.write("hello\nworld\n") with open("notes.txt", encoding="utf-8") as f: content = f.read() print(content)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
hello world
2

Write a new file with the w mode

with open("out.txt", "w", encoding="utf-8") as f: f.write("line 1\nline 2\n") with open("out.txt", encoding="utf-8") as f: print(f.read())

Before you run it, say out loud what it will print. Then open the answer.

What it prints
line 1 line 2
3

Append to the file with the a mode

with open("out.txt", "a", encoding="utf-8") as f: f.write("appended\n") with open("out.txt", encoding="utf-8") as f: print(f.read())

Before you run it, say out loud what it will print. Then open the answer.

What it prints
line 1 line 2 appended
4

Serialise a dict to a JSON file

import json data = {"name": "Ada", "age": 30} with open("data.json", "w") as f: json.dump(data, f, indent=2)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
No terminal output. A new file `data.json` appears next to the script, holding the dict formatted over indented lines: ```json { "name": "Ada", "age": 30 } ```
Open data.json to see the formatted file. json.dump writes the data; json.load reads it back.
5

Load the JSON back into a dict

import json with open("data.json") as f: loaded = json.load(f) print(loaded["name"]) print(loaded["age"])

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada 30

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A file is opened, its contents flow in or out, and the context manager closes it automatically.
1 with opens file in given mode
↓
2 read() loads bytes into a string
↓
3 write() pushes data to disk
↓
4 context exit closes the handle
Why this works
Why use the with statement

Manual file handling risks leaving files open if an error occurs. The with statement is a context manager that calls __exit__ to close the file reliably:

f = open("x.txt")      # risky: may never close
try:
    ...
finally:
    f.close()
# is exactly what `with` does for you

Any object implementing __enter__/__exit__ can be used with with.

When you have a choice

Text vs binary modes

Open text files in text mode ("r", default) with an encoding; open images or archives in binary mode ("rb"/"wb") which returns bytes. Mixing them corrupts data. For large files, read line by line or in chunks instead of loading everything into memory.

Examples

Reading a text file

Read all lines

with open("notes.txt", encoding="utf-8") as f:
    content = f.read()
    print(content)

with opens the file and guarantees it is closed when the block exits, even on error.

Writing and appending

Write new content

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("line 1\nline 2\n")

with open("out.txt", "a", encoding="utf-8") as f:
    f.write("appended\n")

Mode w overwrites; a appends; r reads (default). Always pass encoding for text files.

JSON to and from files

Serialise data

import json
data = {"name": "Ada", "age": 30}
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json") as f:
    loaded = json.load(f)
print(loaded["name"])

json.dump writes, json.load reads; indent makes files readable.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Object-Oriented Programming
Previous Lesson
Object-Oriented Programming
Next Lesson
Generators and Iterators
Generators and Iterators →