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.
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.
#1 Best Overall
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:
Rank #2
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.
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.
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.
Best Value
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.
Quick Recap
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.




