← Cheat Sheets
Python Files, JSON and CSV
Read and write common formats.
# Python Files, JSON and CSV
Read and write common formats.
```python
from pathlib import Path
import json, csv
text = Path("a.txt").read_text(encoding="utf-8")
Path("out.txt").write_text("hello", encoding="utf-8")
with open("a.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.rstrip())
with open("data.json") as f: data = json.load(f)
with open("out.json", "w") as f: json.dump(data, f, indent=2)
with open("a.csv", newline="") as f:
for row in csv.DictReader(f): print(row["name"])
with open("b.csv", "w", newline="") as f:
w = csv.writer(f); w.writerow(["a", "b"])
Path("dir").mkdir(parents=True, exist_ok=True)
list(Path(".").glob("*.py"))
```