Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

How to Save Variables to a File in Python

Save a Python value to a file and load it in a later run. JSON is a simple default for dictionaries and lists; plain text and pickle suit other needs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To keep a Python variable after a program exits, write its value to a file and load it in the next run. For ordinary lists and dictionaries, JSON is a readable, portable default: use json.dump() to save and json.load() to restore. For a single text value, basic file I/O may be enough.

Save and load a dictionary with JSON

JSON works well for common Python data such as dictionaries, lists, strings, numbers, booleans and nested combinations of them. It stores text, so open the file in text mode and specify an encoding.

import json

settings = {"theme": "dark", "volume": 7}

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:
    settings = json.load(file)

print(settings)

The write step creates or replaces settings.json in the program’s current working directory. The read step parses that file back into a Python value, so settings is a dictionary again. The with blocks close the files automatically.

Use "w" when you intend to replace the saved contents. If you need to preserve prior file contents, choose a format and update strategy that matches the data rather than assuming another json.dump() call will merge dictionaries.

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

Save one text value with ordinary file I/O

For a simple string, the built-in file methods are sufficient:

name = "Ada"

with open("name.txt", "w", encoding="utf-8") as file:
    file.write(name)

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

read() returns text. If you save a number this way, convert the text back when loading it—for example, use int() for an integer or float() for a floating-point value. JSON handles common primitive types and their conversions for you.

Choose a storage method for the data

Need Starting point Trade-off
Plain text or one small primitive value Text file I/O You must parse or convert values such as numbers when reading them.
Lists, dictionaries, settings or portable structured data JSON Human-readable and interoperable, but custom objects need explicit conversion.
A richer Python object graph, with both ends controlled and trusted pickle Python-specific and binary; loading untrusted data is unsafe.
A persistent mapping accessed by keys shelve Provides a persistence interface backed by DBM-style storage; check its documented restrictions.
Relational data or database-style queries sqlite3 More structure than saving one serialized object; use it when the data or access pattern calls for a database.

When to use pickle—and its security boundary

pickle can serialize a broader range of Python objects than JSON, but the resulting files are Python-specific and use binary mode:

import pickle

with open("state.pkl", "wb") as file:
    pickle.dump(state, file)

with open("state.pkl", "rb") as file:
    state = pickle.load(file)

Python’s documentation warns: “Only unpickle data you trust.” Unpickling a malicious file can execute code. Use pickle only when you control and trust the file and the source that produced it; do not load a file received from an unknown person or downloaded from an untrusted source.

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

What JSON cannot save directly

JSON does not directly encode every Python type or arbitrary class instance. For unsupported values, convert them into JSON-supported structures—such as dictionaries, lists and primitive values—and write corresponding code to reconstruct the original form after loading.

For a dictionary that needs to survive closing and rerunning a program, the key idea is to persist its value explicitly: load the saved data when the program starts, change the dictionary, then write the updated value back when needed. A Python variable in memory does not persist merely because the program used it.

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.