Reading and writing files

Topic 3 of 4 in Errors and files7 min readBeginnerFree course

Overview

Variables vanish when a program ends. To keep data — notes, settings, scores, reports — you write it to a file, and read it back next time. Python makes text files easy; this lesson covers everything you need for day-to-day file work.

Opening files with with

Opening files with with. with open(“notes.txt”, “w”, encoding=“utf-8”) as f: f.write(“Buy milk\n”) writes a file; with open(“notes.txt”, encoding=“utf-8”) as f: for line in f: print(line.strip()) reads it. The file is closed automatically when the with block ends — even if an error happens. Modes: “r” read (the default) — error if missing; “w” write — creates, or ERASES existing; “a” append — adds to the end; “x” create — error if it exists; “rb” / “wb” binary, for images and zips.

Python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\n")
    f.write("Call Asha\n")
  • open() takes the path, the mode, and the encoding, and returns a file object.
  • with … as f: gives it the name f for the indented block.
  • When the block ends — normally, or because of an error — the file is closed automatically. Always use with: an unclosed file may not have all its data written yet.

Modes

Mode Meaning
"r" read — the default; FileNotFoundError if it doesn’t exist
"w" write — creates the file, or erases it if it exists
"a" append — adds to the end, creating the file if needed
"x" exclusive create — FileExistsError if it already exists
"rb", "wb" binary read/write — images, PDFs, zips (no encoding)

"w" is the dangerous one: open an important file with "w" and its contents are gone before you write anything. Use "a" to add, or "x" to make sure you don’t overwrite.

Always say encoding=“utf-8”

Text files store characters as bytes using an encoding. UTF-8 handles every language and emoji, and is the standard everywhere. Python 3.15 finally uses UTF-8 by default on every system, but on older versions the default depended on the operating system — Windows often used a different one — which caused errors with characters like é, ₹ or 😀. Writing encoding="utf-8" explicitly makes your code behave the same everywhere, on every version.

Writing

Python
with open("scores.txt", "w", encoding="utf-8") as f:
    f.write("Asha,91\n")                     # write() does NOT add a newline
    f.writelines(["Ben,78\n", "Chen,85\n"])  # neither does writelines()
    print("Dee,62", file=f)                  # print() adds one for you

write only accepts strings: convert numbers with str() or an f-string first.

Reading

Python
with open("scores.txt", encoding="utf-8") as f:
    text = f.read()            # the whole file as one string
Python
with open("scores.txt", encoding="utf-8") as f:
    for line in f:             # one line at a time — memory-friendly
        print(line.rstrip())

Each line includes its newline character ("Asha,91\n"). Printing it as-is gives double spacing, because print adds another. Strip it with line.rstrip() (or line.rstrip("\n") to keep other trailing spaces).

Other options:

Python
lines = f.readlines()          # list of lines, each with "\n"
lines = f.read().splitlines()  # list of lines, without "\n"
first = f.readline()           # just the next line

Looping over the file is best for big files: it never holds the whole file in memory.

Handling missing files

Python
try:
    with open("settings.txt", encoding="utf-8") as f:
        settings = f.read()
except FileNotFoundError:
    settings = ""               # first run: no settings yet

Other errors you might meet: PermissionError (not allowed to read or write), IsADirectoryError (the path is a folder).

Paths and pathlib

A relative path like "notes.txt" is relative to the current working directory — the folder the terminal was in when you ran the program, which isn’t necessarily the folder your script is in. That causes many “file not found” surprises.

The pathlib module makes paths easy and portable across Windows, macOS and Linux:

Python
from pathlib import Path

data_dir = Path("data")
data_dir.mkdir(exist_ok=True)              # create the folder if needed
path = data_dir / "notes.txt"              # join with / — works on every OS

path.write_text("Hello\n", encoding="utf-8")
print(path.read_text(encoding="utf-8"))

path.exists()          # True
path.name              # 'notes.txt'
path.stem              # 'notes'
path.suffix            # '.txt'
path.parent            # Path('data')
path.stat().st_size    # size in bytes

for p in data_dir.glob("*.txt"):           # every .txt file in the folder
    print(p.name)

To find files next to your script regardless of where it’s run from:

Python
HERE = Path(__file__).parent
config = HERE / "config.txt"

read_text and write_text are handy one-liners for small files. For anything you process line by line, open() with with is still the tool.

Binary files

Images, audio and other non-text files are read and written as bytes with "rb" and "wb" (and no encoding):

Python
with open("photo.jpg", "rb") as src, open("copy.jpg", "wb") as dst:
    dst.write(src.read())

(For copying, shutil.copy("photo.jpg", "copy.jpg") does it in one call.)

Remember: always with, always encoding="utf-8" for text, be careful with "w", and strip the newlines from lines you read.

Exercise

A simple journal

(1) Write three entries to journal.txt (one per line), overwriting any old file. (2) Append a fourth entry. (3) Read the file back line by line and print each entry numbered from 1, without blank lines in between. (4) Print the total number of words in the file. (5) Try to open missing.txt and print No such file: missing.txt if it doesn’t exist. (6) Using pathlib.Path, print whether journal.txt exists, its suffix, and its size in bytes. Always use encoding="utf-8".

Python
from pathlib import Path

entries = ["Started learning Python", "Wrote my first function", "Fixed a bug by reading the traceback"]

# 1. Write entries

# 2. Append one more

# 3. Read and number the lines

# 4. Count the words

# 5. Handle a missing file

# 6. pathlib information

Summary

  • with open(path, mode, encoding="utf-8") as f: opens a file and closes it automatically, even after an error.
  • Modes: "r" read (default), "w" write (erases!), "a" append, "x" create new; add b for binary.
  • f.read() reads everything; for line in f: reads line by line — lines keep their \n, so strip them.
  • write() doesn’t add newlines; include \n yourself.
  • pathlib.Path handles paths, file names and folders portably; catch FileNotFoundError for missing files.