Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A Python variable disappears when the program ends; writing its value to a file lets a later run read it again. For a basic text file, use open() inside a with block, choose a mode that matches what you want to do, and specify UTF-8 encoding.

How does saving data to a file work?

A running program keeps values in memory. A file gives it a place on the filesystem to write information and retrieve it on a later run. Python’s built-in open() function returns a file object, which provides methods for reading or writing the file.

This example creates notes.txt if it does not exist, or replaces its contents if it does:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Remember this for next time.n")

The with block closes the file when the block ends, including if an error occurs. The Python Software Foundation’s Python 3.14.7 tutorial calls using with good practice for file objects and recommends encoding="utf-8" unless you know another encoding is needed.

Which file mode should you use?

The mode determines whether Python reads, replaces, adds to, or updates the file. Choose it deliberately: in particular, opening a file in w mode clears existing contents.

Mode What it does Use it when
r Reads an existing file. You want to retrieve saved text.
w Creates a file or clears an existing file before writing. You intend to replace the file’s contents.
a Creates a file if needed and writes at the end of an existing file. You want to add new content without replacing what is already there.
r+ Opens a file for both reading and writing. You need both operations on the same file; take care not to overwrite data unintentionally.

How do you read a text file?

Use r to read a file. Calling read() with no size returns all of its contents as one string:

with open("notes.txt", "r", encoding="utf-8") as file:
    contents = file.read()

print(contents)

That is convenient for a small file, but it loads the whole file into memory. For a larger file, process it a line at a time by iterating over the file object:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("notes.txt", "r", encoding="utf-8") as file:
    for line in file:
        process(line)

Replace process(line) with the work your program should perform for each line. The Python tutorial describes file iteration as memory-efficient, fast, and simple; it avoids holding the entire file in memory at once.

How do you append instead of replacing?

Use a when new text should go at the end of a file. For example:

with open("log.txt", "a", encoding="utf-8") as file:
    file.write("Program started.n")

Each call adds text rather than clearing existing contents. Include a newline such as n if you want successive entries on separate lines.

When should you use pathlib?

pathlib.Path represents filesystem paths and offers concise methods for whole-file operations. Use these helpers when you want to read or write a complete, reasonably small file without needing to work directly with modes or stream its contents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

path = Path("notes.txt")
path.write_text("Remember this for next time.n", encoding="utf-8")
contents = path.read_text(encoding="utf-8")

write_text() overwrites an existing file with the same name. The same overwrite caution applies to write_bytes(). For binary content, pathlib also provides read_bytes() and write_bytes(). See the Python Software Foundation’s pathlib documentation for the path-based methods.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do you save a list or dictionary?

For common Python data such as lists and dictionaries, JSON is a readable text format that other programs and languages can exchange. Use the standard-library json module to convert between Python data and JSON:

import json

settings = {"theme": "dark", "notifications": True}

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

with open("settings.json", "r", encoding="utf-8") as file:
    loaded_settings = json.load(file)

json.dump() writes the value to the open file; json.load() reads and converts it back. JSON handles common data types, but a custom class instance needs conversion to a JSON-compatible representation before it can be saved this way.

When should you use text mode or binary mode?

Text mode is for text, read or written as strings. It can decode bytes into characters on reading and encode characters on writing; it may also translate line endings. For ordinary text, specify encoding="utf-8".

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Binary mode uses b in the mode, such as "rb" for reading bytes or "wb" for writing them. Use it for raw data such as an image or executable file, not text methods like read_text(). Treating binary data as text can transform line endings or corrupt the data.

Is pickle safe for saving Python objects?

Python’s pickle module can serialize Python-specific objects, but a pickle file is not a general interchange format and should not be loaded from an untrusted source. The Python documentation warns that deserializing crafted pickle data from an untrusted source can execute arbitrary code. For common lists and dictionaries, JSON is the safer, more interoperable starting point.

Quick choice guide

  • To replace a text file, use "w"; to add to its end, use "a".
  • To read a small text file all at once, use read(); for a larger one, iterate over its lines.
  • For raw bytes, use binary mode or pathlib’s bytes methods.
  • For a list or dictionary you want to store in readable, exchangeable form, use JSON.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.