October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Save Python Data to Files: Read, Write, and Keep It for Next Time

Use Python files to keep data after a program ends. Learn safe text reading and writing, file modes, pathlib shortcuts, JSON for lists and dictionaries, and binary I/O.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python variable lasts only while the program is running; a file lets your program save information for a later run. Use open() to work with a file, choose a mode that matches your goal, and wrap file access in a with block so Python closes it when the block ends.

How do I save data outside my Python program?

For ordinary text, open a file in write mode and specify UTF-8 encoding:

As an Amazon Associate I earn from qualifying purchases.

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Remember this for next time.n")

open() returns a file object, which provides methods for reading or writing. The file is created if it does not exist. If it already exists, "w" clears its contents before writing, so use it only when replacing the old contents is intended.

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

The with block closes the file when execution leaves the block, including when an error occurs. Python’s tutorial calls using with good practice for file objects and recommends encoding="utf-8" for text unless you know you need a different encoding. Python documentation: Input and Output.

Which file mode should I use?

Mode Purpose What to watch for
"r" Read an existing file. Reading fails if the file does not exist.
"w" Write from the beginning; create the file if needed. Clears an existing file before writing.
"a" Append new content to the end; create the file if needed. Does not replace the old content.
"r+" Read and write an existing file. Does not create a missing file; be deliberate about the file position when writing.

For example, append a line without erasing the file:

with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("Another note.n")

How do I read a text file?

Use read mode for a whole-file read:

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

print(contents)

read() without a size reads the entire file into memory. That is convenient for small files, but can be unsuitable when a file is larger than available memory. For line-oriented work or larger files, iterate through the file object instead:

with open("notes.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line, end="")

Iteration processes the file a line at a time rather than first loading all its contents into one string. The Python tutorial describes this approach as memory efficient, fast, and simple.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

When should I use pathlib instead of open()?

pathlib.Path represents filesystem paths and offers concise methods for whole-file operations. Use open() with with when you need to teach or control modes, process incrementally, or stream a file. Use a Path helper when a short whole-file read or write is clearer.

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() replaces the contents of an existing file, just as write mode does. Path also provides read_bytes() and write_bytes() for raw bytes. See the Python pathlib documentation.

How do I save a list or dictionary?

For common Python data such as lists and dictionaries, JSON provides a readable text representation that can also be exchanged with programs written in other languages. Use json.dump() to write an object to a text file and json.load() to read it back:

import json

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

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

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

print(loaded_settings["theme"])

JSON handles common data structures, not arbitrary Python objects. Custom class instances need additional conversion to and from JSON-compatible values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When should I use binary mode or pickle?

Use binary mode for bytes

Text mode is for strings; add b to the mode to work with bytes, such as image or executable-file data. Binary mode does not decode bytes into text or apply text-mode newline transformations. Processing such data as text can corrupt it.

with open("photo.jpg", "rb") as file:
    image_data = file.read()

Treat pickle input as trusted-only

Pickle can serialize arbitrary Python objects, but it is Python-specific and should not be loaded from an untrusted source. The Python documentation warns that “deserializing pickle data coming from an untrusted source can execute arbitrary code” if crafted by a skilled attacker. For common lists and dictionaries, JSON is the safer interoperable choice.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.