Tutorials / Python from Scratch / Reading and writing files

Reading and writing files

14 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

Data that survives

Everything in your variables disappears when the program ends. To keep data, write it to a file. Python makes this easy. You open a file, read or write, and close it.

Writing a text file

lines = ["Invoice 101: 5002.00", "Invoice 102: 1800.00", "Invoice 103: 950.50"]

with open("invoices.txt", "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")

with open("invoices.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(content)

with open("invoices.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip().upper())

with open("invoices.txt", "a", encoding="utf-8") as f:
    f.write("Invoice 104: 300.00\n")

What each part means

open() takes the file name and a mode. The common modes are "r" to read (the default), "w" to write, and "a" to append to the end. Be careful: "w" erases the file if it already exists. This is the most dangerous default in everyday file handling, so double-check the mode before you run.

The with statement closes the file automatically when the indented block ends, even if an error happens in the middle. Always use it. Forgetting to close a file can leave your data half-written.

The encoding="utf-8" argument matters on Windows. Without it Python may use a local encoding, and names with accents or Urdu text can break when the file is opened elsewhere. I add it every time.

Notice that write() does not add a new line for you. You add "\n" yourself. When reading line by line, each line still ends with that newline, which is why we call .strip() before printing.

Reading in different ways

  • f.read() gives the whole file as one string.
  • f.readlines() gives a list of lines.
  • for line in f: reads one line at a time. This is best for large files because it does not load everything into memory.

Paths with pathlib

A relative path like "invoices.txt" is relative to the folder where you run the program, not where the script file sits. That is a common source of "file not found" errors. The pathlib module makes paths clearer.

from pathlib import Path

base = Path(__file__).parent          # folder containing this script
data_file = base / "data" / "invoices.txt"

data_file.parent.mkdir(exist_ok=True)       # create folder if missing
data_file.write_text("hello\n", encoding="utf-8")
print(data_file.read_text(encoding="utf-8"))
print(data_file.exists())                    # True
print(data_file.suffix)                      # .txt

The / operator joins path parts and works on every operating system. Path objects also have handy shortcuts, read_text and write_text, for small files.

Saving structured data as JSON

Text lines are fine for simple notes. For lists and dictionaries, JSON is the usual format. It is human-readable and almost every language understands it.

import json

tasks = [
    {"title": "Pay bill", "done": False},
    {"title": "Call plumber", "done": True},
]

with open("tasks.json", "w", encoding="utf-8") as f:
    json.dump(tasks, f, indent=2)

with open("tasks.json", encoding="utf-8") as f:
    loaded = json.load(f)

print(loaded[1]["title"])    # Call plumber

json.dump writes to a file, and json.load reads from one. Their cousins json.dumps and json.loads (with the extra s) work with strings. Python's True becomes JSON true and None becomes null. JSON keys are always strings, so a dictionary with number keys comes back with text keys.

CSV files

Spreadsheets export to CSV. The csv module handles quotes and commas inside values correctly, which splitting on commas by hand does not.

import csv

with open("sales.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["item", "qty"])
    writer.writerow(["tea", 4])

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

Use newline="" when opening CSV files, otherwise you may get blank lines between rows on Windows.

Common mistakes

  • Opening with "w" and wiping the data. Use "a" to add.
  • Forgetting the file may not exist. Reading a missing file raises FileNotFoundError. We handle that in the next lesson.
  • Reading numbers as text. Everything read from a text or CSV file is a string. Convert with int() or float().
  • Calling json.load on an empty file. It raises an error because an empty file is not valid JSON.

Try it yourself

Write a program that keeps a simple notes file. It asks the user for a note, appends it to notes.txt with the current time, and then prints all notes so far with line numbers. Run it three times and check that the notes accumulate. Get the time with datetime.datetime.now().strftime("%Y-%m-%d %H:%M").

python
lines = ["Invoice 101: 5002.00", "Invoice 102: 1800.00", "Invoice 103: 950.50"]

with open("invoices.txt", "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")

with open("invoices.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(content)

with open("invoices.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip().upper())

with open("invoices.txt", "a", encoding="utf-8") as f:
    f.write("Invoice 104: 300.00\n")

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account