Common File Handling Mistakes
You've covered file handling from every angle. Here are the mistakes that show up most often — and how to fix them.
1. Not closing the file — or forgetting with open()
f = open("soldiers.txt", "r")
content = f.read()
# forgot f.close()
An unclosed file stays locked. Other programs can't access it. On some systems, data doesn't get written until the file is closed.
with open("soldiers.txt", "r", encoding="utf-8") as f:
content = f.read()
# closed automatically — always use this pattern
2. "w" mode — silent overwrite
with open("roster.txt", "w", encoding="utf-8") as f:
f.write("Raven\n")
If roster.txt already exists with a hundred entries — they're gone. No warning. No confirmation. No undo.
Use "w" only when you intend to replace the file completely. Use "a" when you want to keep existing data.
3. FileNotFoundError — wrong path or missing file
with open("data/soldiers.txt", "r") as f:
content = f.read()
Output → FileNotFoundError: [Errno 2] No such file or directory
Python looks for files relative to where the script is run — not where the script is saved. Check the path, check the filename, check the extension.
try:
with open("soldiers.txt", "r", encoding="utf-8") as f:
content = f.read()
except FileNotFoundError:
print("File not found. Check the path.")
4. Missing \n — everything on one line
soldiers = ["Raven", "Wolf", "Ghost"]
with open("roster.txt", "w", encoding="utf-8") as f:
for soldier in soldiers:
f.write(soldier)
Output in file → RavenWolfGhost
write() doesn't add newlines. You add them yourself:
f.write(soldier + "\n")
5. CSV values are strings — forgetting to convert
import csv
with open("soldiers.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["score"] + 10)
Output → TypeError: can only concatenate str (not "int") to str
Every value read from a CSV file is a string. Convert explicitly:
print(int(row["score"]) + 10)
6. Missing newline="" when writing CSV
with open("output.csv", "w", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)
On Windows, this produces blank lines between every row in the CSV.
with open("output.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
Always pass newline="" when writing CSV files.
7. Reading a file twice without reopening
with open("soldiers.txt", "r", encoding="utf-8") as f:
first = f.read()
second = f.read()
print(len(first)) # full content
print(len(second)) # 0 — empty
After read(), the file pointer is at the end. A second read returns nothing.
Open the file again if you need to read it twice — or store the content in a variable and reuse it.
What you should take away
- Always use
with open()— it closes the file automatically "w"overwrites silently — use"a"to preserve existing data- Wrap reads in
try/except FileNotFoundErrorwhen the file might not exist - Add
\nmanually —write()doesn't do it for you - CSV values are strings — convert with
int(),float(),bool() - Pass
newline=""when writing CSV files - A file can only be read once per open — store content in a variable to reuse it