Programming languages · Beginner · 16 min
How to Read and Write Files and JSON in Python
By Padding · Updated 15 Nov 2026
Python 3.15
You will read and write text files with pathlib, convert Python data to JSON and back, and use both to build a small task list that keeps its data in a JSON file and survives a damaged file.
On this page
Almost every program needs to keep something after it exits: a setting, a list, a log. The simplest place is a file. Python reads and writes files with a few lines, and it ships with a json module for the most common format for structured data. Both are in the standard library, so there is nothing to install.
In this tutorial you work with plain text first, then with JSON, and finish with a command-line task list that stores its tasks in a JSON file. The tutorial is the third in the series Python from zero. It uses python3.15 as installed in the first tutorial.
Step 1 · Write and read a text file
Make a folder to work in. Then write a small script that creates a file, reads it back and prints it:
mkdir -p ~/files-demo
cd ~/files-demo
cat > text_files.py <<'PY'
from pathlib import Path
path = Path("hello.txt")
path.write_text("first line\nsecond line\n", encoding="utf-8")
text = path.read_text(encoding="utf-8")
print(repr(text))
print(len(text.splitlines()), "lines")
PY
python3.15 text_files.pyPath from pathlib represents a file location as an object. write_text creates the file, or replaces it if it exists, and read_text returns the whole content as one string. Pass encoding="utf-8" every time, so the script reads the same bytes on every system, whatever its default.
Check it worked
The output is two lines: 'first line\nsecond line\n' with its quotes, which shows the newline characters as \n, and 2 lines. Run cat hello.txt to see the file as the text it holds.
Step 2 · Append and read line by line
write_text replaces what was there. To add to the end of a file, and to read large files without loading them whole, use open inside a with block. The block closes the file for you, even when an error happens:
cat > lines.py <<'PY'
from pathlib import Path
path = Path("hello.txt")
with path.open("a", encoding="utf-8") as f:
f.write("third line\n")
with path.open(encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))
PY
python3.15 lines.pyThe mode "a" means append. With no mode, a file opens for reading text. Looping over the file object gives one line at a time, so memory use stays small however long the file is. enumerate numbers the lines, and rstrip("\n") removes the newline that print would otherwise double.
Check it worked
The output is 1 first line, 2 second line and 3 third line.
Step 3 · Work with paths and folders
A file name is rarely alone. pathlib can build paths, create folders and list files, with / joining the parts on any operating system:
cat > paths.py <<'PY'
from pathlib import Path
data = Path("data") / "notes"
data.mkdir(parents=True, exist_ok=True)
(data / "a.txt").write_text("A\n", encoding="utf-8")
(data / "b.txt").write_text("B\n", encoding="utf-8")
print((data / "a.txt").exists())
print(sorted(p.name for p in data.glob("*.txt")))
print((data / "a.txt").suffix, (data / "a.txt").stem)
PY
python3.15 paths.pymkdir(parents=True, exist_ok=True) creates every missing folder along the way and does nothing if it already exists, so you can run the script twice. glob("*.txt") finds matching files and returns them in no particular order, so sorted makes the output predictable.
Check it worked
The output is True, then ['a.txt', 'b.txt'], then .txt a.
Step 4 · Convert data to JSON and back
JSON is text that describes numbers, strings, booleans, null, lists and objects. Python's dictionaries and lists map onto it directly. json.dumps turns Python data into a JSON string, and json.loads turns a string back into Python data:
cat > json_basics.py <<'PY'
import json
task = {"id": 1, "title": "Buy milk", "done": False, "tags": ["home", "food"]}
as_text = json.dumps(task)
print(as_text)
back = json.loads(as_text)
print(back["title"], back["tags"][0], back["done"])
print(json.dumps(task, indent=2))
PY
python3.15 json_basics.pyCheck it worked
The first line is {"id": 1, "title": "Buy milk", "done": false, "tags": ["home", "food"]}. Python's False became JSON's false. The second line is Buy milk home False: the value came back as a Python False. The last output is the same object spread over several lines, because of indent=2.
Two details cause bugs later. JSON object keys are always strings, so a dictionary with the key 1 comes back with the key "1". And json.dumps raises TypeError for values JSON has no type for, such as datetime objects or sets. Convert them to strings or lists first.
Step 5 · Save and load JSON in a file
json.dump and json.load, without the final s, work on file objects. Most programs only need the path-based form shown here: build the string with dumps and hand it to write_text. The code writes to a temporary file and then renames it over the real one, so an interrupted write leaves the old file in place instead of a half-written one:
cat > json_files.py <<'PY'
import json
from pathlib import Path
store = Path("settings.json")
settings = {"theme": "dark", "font_size": 14, "recent": ["a.txt", "b.txt"]}
tmp = store.with_suffix(".json.tmp")
tmp.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
tmp.replace(store)
loaded = json.loads(store.read_text(encoding="utf-8"))
print(loaded == settings)
print(loaded["recent"])
PY
python3.15 json_files.py
cat settings.jsonCheck it worked
The script prints True and ['a.txt', 'b.txt']. The cat output is the indented JSON, which you can open in any editor or send to another program.
Step 6 · Build a task list
Put the pieces together in a command-line program. It keeps tasks in tasks.json, treats a missing file as an empty list, and stops with a clear message if the file contains something that is not JSON:
cat > tasks.py <<'PY'
import json
import sys
from pathlib import Path
STORE = Path("tasks.json")
def load():
if not STORE.exists():
return []
try:
return json.loads(STORE.read_text(encoding="utf-8"))
except json.JSONDecodeError as err:
sys.exit(f"{STORE} is not valid JSON: {err}")
def save(tasks):
tmp = STORE.with_suffix(".json.tmp")
tmp.write_text(json.dumps(tasks, indent=2) + "\n", encoding="utf-8")
tmp.replace(STORE)
def main(argv):
command = argv[1] if len(argv) > 1 else "list"
tasks = load()
if command == "add":
title = " ".join(argv[2:])
if not title:
sys.exit("usage: tasks.py add <title>")
tasks.append({"id": len(tasks) + 1, "title": title, "done": False})
save(tasks)
print(f"added #{len(tasks)}")
elif command == "done":
if len(argv) != 3 or not argv[2].isdigit():
sys.exit("usage: tasks.py done <id>")
wanted = int(argv[2])
for task in tasks:
if task["id"] == wanted:
task["done"] = True
save(tasks)
print(f"finished #{wanted}")
break
else:
sys.exit(f"no task with id {wanted}")
elif command == "list":
if not tasks:
print("no tasks yet")
for task in tasks:
mark = "x" if task["done"] else " "
print(f"[{mark}] {task['id']} {task['title']}")
else:
sys.exit(f"unknown command: {command}")
main(sys.argv)
PY
python3.15 tasks.py list
python3.15 tasks.py add Buy milk
python3.15 tasks.py add Write the report
python3.15 tasks.py done 1
python3.15 tasks.py listThe for ... else runs its else block only when the loop finishes without break, which is how the program notices an unknown ID.
Check it worked
The first list prints no tasks yet. The two add commands print added #1 and added #2, and done 1 prints finished #1. The last list prints:
[x] 1 Buy milk
[ ] 2 Write the reportRun cat tasks.json to see the data the program stored.
Step 7 · Survive a damaged file
Files get damaged by hand edits, full disks and half-finished copies. Break the file on purpose to see what the program does:
echo "this is not json" > tasks.json
python3.15 tasks.py list || echo "exit status $?"The program prints tasks.json is not valid JSON: ` followed by the parser's description of where it failed, then exits with status 1 instead of showing a long traceback, and the shell prints `exit status 1. It does not overwrite the file, so the data is still there to repair.
Before you move on, delete the demo folder:
cd ~
rm -rf ~/files-demoNext steps
- Fetch JSON from the web instead of a file: call a web API from Python with httpx.
- Check that code like
tasks.pykeeps working as you change it: write and run tests with pytest. - The
pathlibandjsonpages in the Python documentation at docs.python.org list everything else these modules do.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials