Files, JSON and pathlib
Read and write text and JSON safely and handle paths without string tricks.
Open files with with. It closes the file for you, even if an error happens.
from pathlib import Path
path = Path("data") / "notes.txt"
path.parent.mkdir(exist_ok=True)
with path.open("w", encoding="utf-8") as f:
f.write("hello\n")
text = path.read_text(encoding="utf-8")- Always pass
encoding="utf-8". The default depends on the system. pathlib.Pathjoins paths with/and works on Windows, macOS and Linux.- Modes:
"r"read,"w"overwrite,"a"append,"b"binary.
JSON
import json
data = {"name": "Ana", "tags": ["a", "b"]}
Path("data.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
loaded = json.loads(Path("data.json").read_text(encoding="utf-8"))
print(loaded["tags"])dumps and loads work with strings. dump and load work with open files. JSON only supports strings, numbers, booleans, null, lists and objects, so dates and custom classes need converting first.
Large files
Do not read a huge file at once. Loop over it and Python reads one line at a time.
with open("big.log", encoding="utf-8") as f:
for line in f:
if "ERROR" in line:
print(line.rstrip())CarefulNever build a path with user input directly. A name like ../../etc/passwd can escape your folder. Check the final path with resolve() and make sure it is inside the folder you expect.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.