Sooner or later every program needs to read or save data. Python makes this simple, but there are a few habits that prevent lost data and strange errors. This guide covers text files, the with statement, CSV and JSON, with examples you can run.
Write a text file
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("First line\n")
f.write("Second line\n")open() takes the file name and a mode. The common modes are "r" to read (the default), "w" to write (this erases an existing file), "a" to append to the end, and "x" to create a file and fail if it already exists. Always pass encoding="utf-8"; the default depends on the system and is a common source of broken characters.
Why use with
A file must be closed after use, or data may not be saved. The with statement closes it for you automatically, even if an error happens inside the block. Always open files this way.
Read a text file
with open("notes.txt", encoding="utf-8") as f:
text = f.read() # the whole file as one string
print(text)
with open("notes.txt", encoding="utf-8") as f:
for line in f: # one line at a time, good for big files
print(line.strip())Looping over the file reads one line at a time and keeps memory use low, which matters for large files. .strip() removes the newline at the end of each line.
Handle a missing file
try:
with open("missing.txt", encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
print("That file does not exist")Paths with pathlib
The pathlib module builds paths that work on every operating system and has shortcuts for reading and writing:
from pathlib import Path
folder = Path("data")
folder.mkdir(exist_ok=True)
file = folder / "greeting.txt" # the / joins path parts
file.write_text("hello", encoding="utf-8")
print(file.read_text(encoding="utf-8")) # hello
print(file.exists()) # TrueCSV files
Use the built-in csv module rather than splitting lines yourself, because it handles commas and quotes inside values.
import csv
rows = [{"name": "Asha", "city": "Kochi"}, {"name": "Ravi", "city": "Pune"}]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "city"])
writer.writeheader()
writer.writerows(rows)
with open("people.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], "lives in", row["city"])The newline="" argument stops blank lines appearing between rows on Windows. DictReader gives each row as a dictionary, using the header row for the keys.
JSON files
JSON is the usual format for saving structured data and for talking to web services. Python dictionaries and lists convert directly:
import json
data = {"name": "Asha", "skills": ["python", "sql"], "active": True}
with open("profile.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("profile.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["skills"]) # ['python', 'sql']json.dump writes to a file and json.load reads from one. For strings, use json.dumps and json.loads (the "s" stands for string). Paste your JSON into our JSON formatter if you want to check it is valid.
Quick reference
| Task | Code |
|---|---|
| Read all text | open(p, encoding="utf-8").read() inside a with |
| Write text | open(p, "w", encoding="utf-8") |
| Add to the end | open(p, "a", encoding="utf-8") |
| Check a file exists | Path(p).exists() |
| Save a dictionary | json.dump(data, f) |
Next, learn how to fetch JSON from a web API, or review the built-in data structures that you will be saving.
Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.
