Lesson 10 of 34 · 0 of 2 exercises solved
File I/O
Reading and writing files is how programs keep data between runs. The "with" statement opens a file and closes it again automatically, even if an occurs.
# Reading files
# open(path, mode) — mode: 'r' read, 'w' write, 'a' append, 'b' binary
# Read entire file
with open("hello.txt", "r") as f:
content = f.read()
print(content)
# Read line by line (memory-efficient for large files)
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes trailing newline
# Read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines() # each line includes \n
lines = [l.strip() for l in lines]
# Writing files
with open("output.txt", "w") as f: # 'w' overwrites!
f.write("Hello, file!\n")
f.write("Second line\n")
# Appending
with open("log.txt", "a") as f:
f.write("New log entry\n")
# Writing multiple lines at once
lines = ["line 1\n", "line 2\n", "line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)import json
import csv
from pathlib import Path
# JSON
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}
# Write JSON
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
# CSV
rows = [
["name", "age", "city"],
["Alice", "30", "Paris"],
["Bob", "25", "Berlin"],
]
with open("people.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
with open("people.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['name']} lives in {row['city']}")
# pathlib — modern path handling
p = Path("data")
p.mkdir(exist_ok=True) # create directory
(p / "file.txt").write_text("hello") # write
text = (p / "file.txt").read_text() # read
print(list(p.glob("*.txt"))) # find files
print(p.exists()) # TrueCommon question
Does it matter if I close a file after reading it?
A file object is a handle on something the owns. Opening it grabs the resource; closing it releases the handle and flushes any buffered writes. The with statement ties both to a block, so the file is closed on the way out no matter how the block ends. It is the same context-manager mechanism used for locks and network connections.
Name the encoding when reading text, over large files line by line, and pick the mode carefully: "r" reads, "w" replaces, "a" appends, "x" creates and fails if the file exists. For structured data, use the csv and json instead of parsing by hand, and pathlib.Path for paths that work on every operating system.
Source: The Python tutorial: "It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes."
Common mix-ups
Each of these sounds reasonable. Think about why it is wrong, then open the explanation.
Python has garbage collection, so an unclosed file gets closed eventually and no harm is done.
Reading a whole file with read() is always fine.
Opening a file with mode "w" adds to whatever is already there.
Practice
This sandbox has a real (virtual) file system. Write the three lines in the to notes.txt, one per line, then read the file back and count how many lines it contains. Use with blocks for both operations.
Write, then read
lines = ["Buy oat milk", "Finish lesson 10", "Call Grandma"]
# write notes.txt
# read it back and count the lines
line_count = 0
print(line_count)
Press Run to try your code, then Check answer to grade it.Use the csv module to write the expense rows to expenses.csv with a header row, then read the file back with csv.DictReader and compute total as the sum of the amount column.
CSV round trip
import csv
expenses = [
{"item": "coffee", "amount": 3.5},
{"item": "book", "amount": 12.0},
{"item": "lunch", "amount": 9.25},
]
# write expenses.csv with a header
# read it back and total the amounts
total = 0
print(total)
Press Run to try your code, then Check answer to grade it.Check yourself
What happens when you open an existing file with mode "w"?
Tip: use the ← and → keys to move between lessons.