File Operations & JSON in Python

From the Python cheat sheet ยท File I/O ยท verified Jul 2026

File Operations & JSON

Read, write, and append files. Parse and write JSON data.

python
# Read a file
with open("data.txt") as f:
    content = f.read()

# Write a file
with open("output.txt", "w") as f:
    f.write("Hello!")

# JSON
import json
data = json.loads('{"name": "Alice"}')
json_str = json.dumps(data, indent=2)
๐Ÿ’ก Always use "with open(...)" โ€” it automatically closes the file
โšก json.load/dump work with files; json.loads/dumps work with strings
๐Ÿ“Œ Use pathlib.Path for cross-platform path handling โ€” it's the modern approach
๐ŸŸข Read large files line-by-line with "for line in f:" to save memory
filesjsonio
Back to the full Python cheat sheet