Ravindra BagaleCourses & study guides मराठी Track your progress

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

  1. Check Path(file).exists().
  2. Use try/except FileNotFoundError.
  3. 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.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.