Many programs need to keep something after they stop running: a score, a log or a list of settings. By the end of this guide, you will be able to create a text file in Python, read it back in full or line by line, add to it without erasing it and save lists and dictionaries as JSON.

The steps follow the “Reading and writing files” section of the official Python tutorial and the reference entry for open() on the built-in functions page. Every example was run with Python 3.14 in an empty folder, and its real output appears in the block below the code.

1. Open a file with open() and with

open(filename, mode) returns a file object. The mode is a short string that says what you plan to do:

  • "r" reads the file. This is the default if you leave the mode out.
  • "w" writes, and erases any existing file with the same name.
  • "a" appends, adding new text to the end.
  • "x" creates a new file and fails if one already exists.
  • Adding "b", as in "rb", opens the file in binary mode.

Open files inside a with block. The tutorial explains that the file is closed properly when the block finishes, even if an error is raised partway through.

2. Write text to a file

with open("notes.txt", "w", encoding="utf-8") as f:
    count = f.write("First linen")
    f.write("Second linen")
print(count)
print(f.closed)
11
True

write() returns the number of characters it wrote: the 10 characters of First line plus the newline n. It does not add a newline for you, so end each line with n yourself. After the block, f.closed is True.

3. Read the whole file

with open("notes.txt", encoding="utf-8") as f:
    text = f.read()
print(repr(text))
'First linenSecond linen'

read() with no argument returns the entire file as one string. That is fine for small files, but the tutorial points out that it loads everything at once, so a file larger than your computer’s memory becomes a problem.

4. Read one line at a time

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

The tutorial describes looping over the file object as memory efficient and fast. Each line keeps its newline at the end, which is why the example calls strip(). To get every line in a list, use f.readlines() or list(f).

5. Add to a file without erasing it

with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("Third linen")
with open("notes.txt", encoding="utf-8") as f:
    print(f.readlines())
['First linen', 'Second linen', 'Third linen']

6. Save lists and dictionaries as JSON

Writing numbers and nested data by hand gets messy. The standard json module converts Python data to JSON (JavaScript Object Notation), a common data exchange format, and back again.

import json
course = {"title": "Python basics", "scores": [78, 91, 85]}
with open("course.json", "w", encoding="utf-8") as f:
    json.dump(course, f)
with open("course.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded["scores"][1])
91

json.dump() writes the data to the file, and json.load() rebuilds it as a Python dictionary. The tutorial notes that JSON files must be encoded in UTF-8.

Why the examples pass encoding=”utf-8″

In text mode, Python turns the bytes on disk into strings using an encoding. The reference for open() says that in Python 3.15, UTF-8 became the default, replacing the platform-dependent locale encoding used by earlier versions. On those versions, the default depends on the computer’s settings. Passing encoding="utf-8" gives the same result everywhere. Binary mode takes no encoding at all.

Common mistakes

  • Erasing a file by accident. Mode "w" wipes an existing file. Use "a" to add to it, or "x" to refuse to overwrite. Opening the existing notes.txt with "x" ends with FileExistsError: [Errno 17] File exists: 'notes.txt'.
  • Using the wrong path. A relative file name is looked up from the current working directory, which is not always the folder that holds your script. A typo gives FileNotFoundError: [Errno 2] No such file or directory: 'note.txt'.
  • Reading a closed file. Calling f.read() after the file is closed raises ValueError: I/O operation on closed file. Do all your reading inside the with block.
  • Skipping with and close(). The tutorial warns that without with or f.close(), data passed to write() might not be completely written to disk, even if the program exits successfully.
  • Opening images in text mode. Text mode converts line endings, which the tutorial says will corrupt binary data such as JPEG images or EXE program files. Use "rb" and "wb" for those.

With open(), the right mode and a with block, you can handle most everyday file tasks. Write with "w", add with "a", read with a loop, and use json when the data has structure. Naming the encoding keeps your files readable on any machine.