Write code to perform file-processing operations
20.2 File Processing and Exception Handling
What is File Processing?
File processing means reading data from a file, writing data to a file, or updating existing files. In most programming languages (e.g., Python) we treat a file as a stream of bytes or characters.
Common File Modes
| Mode | Meaning | Typical Use |
|---|---|---|
r |
Read (file must exist) | Loading data |
w |
Write (creates new or truncates) | Saving output |
a |
Append (write at end) | Logging |
r+ |
Read and write | Updating records |
b (e.g., rb) |
Binary mode | Images, compiled files |
Opening a File – Basic Syntax (Python)
# Open a text file for reading
file = open("data.txt", "r") # returns a file object
# Read the whole content
content = file.read()
# Always close when done
file.close()
Using with (Context Manager)
The with statement automatically closes the file, even if an error occurs.
with open("data.txt", "r") as f:
lines = f.readlines() # list of lines
for line in lines:
print(line.strip())
Writing to a File
with open("output.txt", "w") as f:
f.write("Hello, Cambridge A-Level!")
f.write(f"The value of pi is approximately {3.14159:.5f}")
Exception Handling – Why It Matters
File operations can fail (file not found, permission denied, disk full). Using try…except lets the program respond gracefully instead of crashing.
Try‑Except‑Finally Pattern
try:
f = open("missing.txt", "r")
data = f.read()
except FileNotFoundError:
print("Sorry, the file does not exist.")
except PermissionError:
print("You do not have permission to read this file.")
else:
print("File read successfully.")
print(f"First 100 characters: {data[:100]}")
finally:
# This runs no matter what
if 'f' in locals() and not f.closed:
f.close()
print("Cleanup complete.")
Specific Exceptions for File I/O
FileNotFoundError– file does not exist.PermissionError– insufficient rights.IsADirectoryError– tried to open a directory as a file.IOError(orOSError) – generic I/O problem.
Example: Processing a CSV File
Assume students.csv contains: name,age,grade lines.
import csv
try:
with open("students.csv", "r", newline='') as csvfile:
reader = csv.DictReader(csvfile)
total_age = 0
count = 0
for row in reader:
total_age += int(row["age"])
count += 1
print(f"{row['name']} is {row['age']} years old, grade {row['grade']}")
if count > 0:
avg = total_age / count
print(f"Average age: ${avg:.2f}$")
except FileNotFoundError:
print("Error: students.csv not found.")
except ValueError:
print("Error: non‑numeric age encountered.")
except Exception as e:
print(f"Unexpected error: {e}")
Best Practices
- Always use
withwhen possible – guarantees closure. - Catch specific exceptions; avoid bare
except:. - Provide meaningful error messages to the user.
- Close resources in a
finallyblock if you don’t usewith. - When dealing with large files, read line‑by‑line or use chunks to avoid high memory usage.
- For binary files (images, compiled code) use modes like
'rb'and'wb'.
Quick Checkpoint
- What is the difference between
'w'and'a'modes? - Why is
finallyuseful even when an exception is caught? - Write one line of code that opens
log.txtfor appending and writes a timestamp.
End of 20.2 File Processing and Exception Handling notes
Revision
Log in to practice.
2 views
0 suggestions