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