Module 7 · Beginner · Files and error handling

Python file handling: read, write, CSV, JSON

Python file handling for beginners: open, read and write text files with with, file modes, CSV and JSON, try/except for errors, plus practice questions.

By theprogrammers team · · 5 min read

Programs forget everything when they stop, unless they save it to a file. File handling is how Python reads data in and writes results out: logs, reports, settings, and the CSV and JSON files you'll meet in almost every real project.

This guide covers opening files safely with with, file modes, reading and writing text, CSV and JSON, file paths, and handling errors with try and except.

Writing and reading a text file

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

with open("notes.txt", encoding="utf-8") as f:
    text = f.read()
print(text)
  • open(path, mode) returns a file object.
  • The with block closes the file automatically when it ends, even if an error happens inside. Always use it.
  • write doesn't add a newline for you; include \n yourself.
  • encoding="utf-8" avoids surprises with characters like ₹ or Hindi text, especially on Windows, where the default encoding can differ.

File modes

ModeMeaningIf the file existsIf it doesn't
"r"Read (the default)Reads itFileNotFoundError
"w"WriteEmpties it firstCreates it
"a"AppendAdds to the endCreates it
"x"CreateFileExistsErrorCreates it

Add b for binary files such as images: "rb", "wb". Be careful with "w": it erases the file the moment it opens it.

Reading line by line

Looping over a file gives one line at a time, which works even for files too big to fit in memory:

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())    # strip() removes the trailing newline

Other options: f.readlines() returns a list of all lines, and f.read().splitlines() does the same without the newline characters.

Appending to a file

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Backup finished\n")

CSV files

CSV (comma-separated values) is the format spreadsheets export. Use the built-in csv module rather than splitting on commas yourself, because values can contain commas inside quotes:

import csv

rows = [
    {"name": "Ahana", "marks": 88},
    {"name": "Rohan", "marks": 72},
]
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "marks"])
    writer.writeheader()
    writer.writerows(rows)

with open("marks.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], int(row["marks"]))

Two details matter:

  • Open CSV files with newline="". Without it, you get blank lines between rows on Windows.
  • DictReader gives every value as a string, so convert numbers yourself with int() or float().

For analysing large CSV files, pandas reads them into a table in one line.

JSON files

JSON is the format web APIs use, and it maps directly onto Python dictionaries and lists:

import json

contacts = {"Ahana": "98765 43210", "Rohan": "91234 56789"}
with open("contacts.json", "w", encoding="utf-8") as f:
    json.dump(contacts, f, indent=2)

with open("contacts.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded["Ahana"])    # 98765 43210

json.dump and json.load work with files. json.dumps and json.loads (with an s, for string) convert to and from a string.

Handling errors with try and except

Files go missing, and users type letters where you expected numbers. Instead of crashing, catch the error and decide what to do:

try:
    with open("settings.json", encoding="utf-8") as f:
        settings = json.load(f)
except FileNotFoundError:
    settings = {}          # first run: start with no settings
except json.JSONDecodeError:
    print("settings.json is damaged; using defaults.")
    settings = {}

The full form has two more optional parts:

try:
    n = int(input("Enter a number: "))
except ValueError:
    print("That wasn't a number.")
else:
    print(f"Double it: {n * 2}")    # runs only if there was no error
finally:
    print("Done.")                  # always runs

Catch specific errors. A bare except: also hides bugs you didn't expect, such as a typo in a variable name, and makes them much harder to find.

Common errors you will meet

ErrorUsual cause
FileNotFoundErrorWrong name, or the program runs from a different folder than you think
PermissionErrorThe file is open in another program, or you can't write to that folder
UnicodeDecodeErrorThe file isn't UTF-8; check how it was saved
ValueErrorConverting text that isn't a number, as in int("abc")

File paths

A relative path like "data/marks.csv" is relative to the folder you run the program from, not the folder the script is in. The pathlib module makes paths clearer and works on every operating system:

from pathlib import Path

data = Path(__file__).parent / "data" / "marks.csv"   # next to this script
print(data.exists())
text = data.read_text(encoding="utf-8")

Practice

  1. Write a list of three city names to cities.txt, one per line, then read them back into a list.
Show the answer
cities = ["Kanpur", "Lucknow", "Agra"]
with open("cities.txt", "w", encoding="utf-8") as f:
    for c in cities:
        f.write(c + "\n")

with open("cities.txt", encoding="utf-8") as f:
    loaded = f.read().splitlines()
print(loaded)    # ['Kanpur', 'Lucknow', 'Agra']
  1. Count the lines in a text file that contain the word "error".
Show the answer
count = 0
with open("log.txt", encoding="utf-8") as f:
    for line in f:
        if "error" in line.lower():
            count += 1
print(count)

lower() makes it match "Error" and "ERROR" too.

  1. Ask the user for their age, and keep asking until they type a valid whole number.
Show the answer
while True:
    try:
        age = int(input("Age: "))
        break
    except ValueError:
        print("Please type a whole number.")
  1. Load contacts.json if it exists, or start with an empty dictionary if it doesn't.
Show the answer
import json

try:
    with open("contacts.json", encoding="utf-8") as f:
        contacts = json.load(f)
except FileNotFoundError:
    contacts = {}

Interview questions

Why use with open() instead of open() and close()?

with closes the file automatically when the block ends, even if an exception is raised inside it. With a manual close(), an error before that line leaves the file open.

What is the difference between the "w" and "a" modes?

"w" empties the file when it opens it, then writes from the start. "a" keeps the existing content and adds to the end. Both create the file if it doesn't exist.

What is the difference between json.load and json.loads?

json.load reads JSON from a file object. json.loads parses JSON from a string. Likewise, json.dump writes to a file and json.dumps returns a string.

When do the else and finally blocks of a try statement run?

else runs only if the try block raised no exception. finally always runs, error or not, which makes it the place for clean-up code.

What to learn next

  1. Build the roadmap's stage 4 project: a contact book that saves to JSON. See the Python roadmap.
  2. Load and analyse CSV files with pandas DataFrames.