Python File Handling and Exceptions -
Practical Guide
A concise 10-page introduction to reading files, writing structured data, and handling errors safely.
1. Working with text files
Python can read and write text files with the built-in open function. The recommended approach is to
use a with statement so the file is closed automatically even if an error occurs.
with open("[Link]", "r", encoding="utf-8") as f:
content = [Link]()
print(content)
Explicitly specifying an encoding such as UTF-8 improves portability across operating systems and
environments.
Page 1
2. File modes
Common file modes include r for reading, w for writing and replacing existing content, a for appending,
and x for creating a new file only if it does not already exist.
with open("[Link]", "a", encoding="utf-8") as f:
[Link]("Process finished\n")
Binary modes add the letter b, such as rb or wb. Binary mode is appropriate for images, archives, and
other non-text formats.
Page 2
3. Reading efficiently
The read method loads data from a file, readline reads one line, and direct iteration reads line by line.
Iteration is a good choice for large files because it avoids loading the entire file into memory.
with open("[Link]", encoding="utf-8") as f:
for line in f:
line = [Link]("\n")
print(line)
For very large datasets, processing one line or chunk at a time can reduce memory usage substantially.
Page 3
4. Writing structured text
When writing data, decide whether a plain text format is sufficient or whether a structured format such
as CSV or JSON is more appropriate. Structured formats make data easier to exchange between
programs.
lines = ["apple", "banana", "mango"]
with open("[Link]", "w", encoding="utf-8") as f:
[Link]("\n".join(lines))
Always consider how special characters, separators, and newlines should be represented when
designing a file format.
Page 4
5. CSV files
The standard csv module handles quoting and delimiter rules for comma-separated data. Using the
module is safer than manually splitting lines on commas.
import csv
with open("[Link]", newline="", encoding="utf-8") as f:
reader = [Link](f)
for row in reader:
print(row)
CSV files vary in delimiter, quoting conventions, and character encoding, so production code may need
configuration for external data sources.
Page 5
6. JSON files
JSON is commonly used for configuration files and API data. Python provides the json module for
converting between JSON text and Python objects.
import json
data = {"name": "Mango", "qty": 100}
with open("[Link]", "w", encoding="utf-8") as f:
[Link](data, f, ensure_ascii=False, indent=2)
JSON supports objects, arrays, strings, numbers, booleans, and null. Python dictionaries and lists map
naturally to JSON objects and arrays.
Page 6
7. Handling exceptions
File operations can fail because a file does not exist, permissions are insufficient, the disk is full, or the
data is malformed. Use try and except to handle expected failures.
try:
with open("[Link]", encoding="utf-8") as f:
text = [Link]()
except FileNotFoundError:
text = "{}"
Catch specific exception types whenever possible. A broad except clause can hide programming errors
that should instead be fixed.
Page 7
8. else and finally in exception handling
A try statement can include else and finally. The else block runs only when no exception occurs, while
the finally block runs regardless of whether an exception was raised.
try:
value = int("42")
except ValueError:
print("Invalid number")
else:
print("Parsed:", value)
finally:
print("Finished")
The finally block is useful for cleanup that must always happen, although context managers often
provide a cleaner solution for files and other resources.
Page 8
9. Raising your own exceptions
Use raise when a function detects invalid state or input that it cannot sensibly handle. Raising an
exception separates error detection from error handling.
def set_quantity(qty):
if qty < 0:
raise ValueError("Quantity cannot be negative")
return qty
Custom exception classes can make large applications easier to debug by distinguishing
domain-specific failures from generic built-in errors.
Page 9
10. Reliable file-processing workflow
A robust workflow validates paths, uses explicit encodings, handles expected exceptions, preserves
original data when possible, and writes output atomically when data integrity matters.
• Use with statements for automatic resource cleanup.
• Prefer specific exception classes.
• Validate parsed data before using it.
• Keep backups when overwriting important files.
• Log enough context to diagnose failures without exposing secrets.
Combining careful file handling with precise exception handling produces programs that fail predictably
and are much easier to operate in real environments.
Page 10