Chapter 10 of 12
Reading and writing files is one of Python's most useful capabilities for automation, data processing, and building tools. Python's context manager syntax makes it clean and safe.
# The 'with' statement โ automatically closes the file
# (even if an exception is raised)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # entire file as a string
# Read line by line (memory efficient for large files)
with open("large_file.txt", "r") as f:
for line in f:
line = line.strip() # remove trailing newline
process(line)
# Read all lines into a list
with open("courses.txt", "r") as f:
lines = f.readlines() # ["HTML
", "CSS
", "Python
"]
lines = [l.strip() for l in lines] # clean up newlines# Writing (overwrites if file exists)
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Line 1
")
f.write("Line 2
")
# Appending (adds to existing file)
with open("log.txt", "a") as f:
f.write(f"[2025-01-15] Server started
")
# Writing multiple lines
lines = ["apple", "banana", "mango"]
with open("fruits.txt", "w") as f:
f.writelines(line + "
" for line in lines)
# JSON โ the most common format for data exchange
import json
# Write Python dict/list to JSON file
data = { "courses": 12, "students": 1500, "active": True }
with open("stats.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON file into Python dict
with open("stats.json", "r") as f:
data = json.load(f)
# Convert without file
json_string = json.dumps(data, indent=2) # dict โ string
data = json.loads(json_string) # string โ dictTIP
Always use with when opening files. The with statement ensures the file is properly closed even if your code raises an exception. Unclosed files can cause data corruption and resource leaks. There's almost never a reason to use the old f = open() / f.close() pattern.