Working with Files in Python: Read, Write, and Handle Errors
Introduction
Most real programs need to read from or write to files. Python's open() function and the with statement make this straightforward and make sure files are closed properly even when something goes wrong. This tutorial covers reading, writing, appending, and handling common errors.
Prerequisites
- Python 3.8 or newer installed
- Basic knowledge of strings and for-loops
Step-by-Step Guide
Step 1: Read a whole file
Open the file inside a with block so it is closed automatically. Pass encoding explicitly so behavior is the same on every operating system.
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)Step 2: Read a file line by line
Looping over the file object reads one line at a time, which is memory-friendly for large files.
with open("notes.txt", encoding="utf-8") as file:
for line in file:
print(line.strip())Step 3: Write and append
Mode 'w' creates the file or overwrites it. Mode 'a' adds to the end of an existing file.
with open("output.txt", "w", encoding="utf-8") as file:
file.write("First line\n")
with open("output.txt", "a", encoding="utf-8") as file:
file.write("Second line\n")Step 4: Handle missing files
Wrap file access in try/except to catch FileNotFoundError and respond sensibly instead of crashing.
try:
with open("missing.txt", encoding="utf-8") as file:
data = file.read()
except FileNotFoundError:
print("File not found.")Step 5: Use pathlib for shorter code
The pathlib module offers one-line helpers for simple reads and writes and works with file paths in a cross-platform way.
from pathlib import Path
text = Path("notes.txt").read_text(encoding="utf-8")
Path("copy.txt").write_text(text, encoding="utf-8")FAQs
- Why use the with statement?
- with guarantees the file is closed when the block ends, even if an exception is raised, so you don't leak file handles or lose buffered data.
- What is the difference between 'w' and 'a' mode?
- 'w' erases any existing content before writing, while 'a' keeps it and adds new text at the end.
Summary
Open files with with, specify an encoding, pick the right mode for the job, and catch errors like FileNotFoundError. For simple cases, pathlib keeps the code short.
Comments
Log in or create a free account to join the discussion.