How to Read and Write CSV, JSON and Text Files in Python (with open and with)
P9.6 Common File Errors in Python and How to Fix Them
Why. File errors are frequent and almost always quick to fix once you know them.
| Error | Cause | Fix |
|---|---|---|
| FileNotFoundError | wrong name or wrong folder | print os.getcwd(); check spelling and extension |
| UnicodeDecodeError | file is not UTF-8 (often Excel CSV) | try encoding="utf-8-sig" or "cp1252" |
| PermissionError | file is open in Excel | close Excel and try again |
| Empty lines in CSV | missing newline="" | add newline="" when writing |
How to read this table: each row is one file error, its usual cause and the fix.
How.
Open a file safely
- Check
Path(file).exists(). - Use try/except FileNotFoundError.
- Give a clear message if it is missing.
Worked example A — Handle a missing file.
Step 1 — What we do. We try to open a report that has not been exported yet.
Step 2 — Type and run this code.
try:
with open("april.csv", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("april.csv not found - export it first")
Step 3 — Output you should see.
april.csv not found - export it first
Step 4 — What it means. The program explains the problem instead of crashing.
Ravindra Bagale's Tip
Excel CSV files often start with a hidden BOM character. encoding="utf-8-sig" removes it, so your first column name is clean.
Ravindra Bagale's Tip – मराठी
Excel च्या CSV files मध्ये सुरुवातीला लपलेलं BOM अक्षर असतं. encoding="utf-8-sig" ते काढतं, त्यामुळे पहिल्या column चं नाव स्वच्छ राहतं.
Ravindra Bagale's Tip – हिंदी
Excel की CSV files की शुरुआत में छिपा BOM अक्षर होता है. encoding="utf-8-sig" उसे हटाता है, तो पहले column का नाम साफ़ रहता है.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.