B2.5.1
Construct code to perform file-processing operations
A file is a named collection of data stored on secondary storage (e.g., hard drive, SSD). Files allow data to persist after a program ends — unlike…
What is a File?
A file is a named collection of data stored on secondary storage (e.g., hard drive, SSD). Files allow data to persist after a program ends — unlike variables in RAM, which are lost when the program exits.
File Paths
| Term | Meaning |
|---|---|
| Absolute path | Full path from the root of the file system — e.g., C:\Users\Michael\data.txt |
| Relative path | Path relative to the current working directory — e.g., data/sample.txt |
File Modes
Before opening a file, you must specify the mode — what operation you intend to perform.
| Mode | Character | Description | Creates file? | Overwrites? |
|---|---|---|---|---|
| Read | r | Read from file (default) | ❌ No | ❌ No |
| Write | w | Write to file | ✅ Yes | ✅ Yes (truncates) |
| Append | a | Append to end of file | ✅ Yes | ❌ No |
| Read+Write | r+ | Read and write | ❌ No | ❌ No |
| Write+Read | w+ | Write and read | ✅ Yes | ✅ Yes |
| Append+Read | a+ | Append and read | ✅ Yes | ❌ No |
Opening and Closing Files
The Old Way (Manual)
file = open("data.txt", "r")
content = file.read()
file.close()
The with Statement (Context Manager) — Recommended
The with statement automatically closes the file when the block exits, even if an exception occurs:
with open("data.txt", "r") as file:
content = file.read()
# File is automatically closed here
with open("data.txt", "w") as file:
file.write("Hello, World!")
# File is automatically closed here
Reading Files
Read Entire File as a String
with open("data.txt", "r") as file:
content = file.read()
print(content)
Read Specific Number of Characters
with open("data.txt", "r") as file:
first_10 = file.read(10) # Read first 10 characters
Read One Line at a Time
with open("data.txt", "r") as file:
line1 = file.readline() # Read the first line (includes '\n')
line2 = file.readline() # Read the second line
Read All Lines into a List
with open("data.txt", "r") as file:
lines = file.readlines() # Returns a list of all lines
for line in lines:
print(line, end="")
Iterate Line by Line (Memory Efficient)
with open("data.txt", "r") as file:
for line in file:
print(line, end="")
Writing Files
Write a String (Overwrites)
with open("output.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
Write Multiple Lines (writelines)
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
Append to a File
with open("output.txt", "a") as file:
file.write("Appended line\n")
Common Exceptions in File Processing
| Exception | Cause |
|---|---|
FileNotFoundError | Trying to read a file that doesn’t exist |
PermissionError | No permission to read/write the file |
IsADirectoryError | Path points to a directory, not a file |
UnicodeDecodeError | File cannot be decoded with the given encoding |
Handling File Exceptions
try:
with open("missing.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File does not exist.")
except PermissionError:
print("You do not have permission to access this file.")
else:
print("File read successfully.")
Best Practices Summary
| Practice | Why it matters |
|---|---|
Always use with statement | Guarantees file closure, even on exceptions |
Use encoding="utf-8" | Handles international characters correctly |
| Check if file exists before reading | Prevents FileNotFoundError crashes |
Avoid mode w when preserving data | Use a to append, not overwrite |