Program 1
Write to a file
Create and write text to a file.
python
with open("notes.txt", "w") as f:
f.write("Python is fun!
")
f.write("Keep practicing.
")Topic 11 of 17
Read and write text, JSON, and CSV files safely.
Program 1
Create and write text to a file.
with open("notes.txt", "w") as f:
f.write("Python is fun!
")
f.write("Keep practicing.
")Program 2
Iterate over file lines.
with open("notes.txt") as f:
for line in f:
print(line.strip())Program 1
Serialize Python dicts to JSON.
import json
data = {"name": "Ada", "skills": ["Python", "Math"]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
with open("data.json") as f:
loaded = json.load(f)
print(loaded)Program 1
Use the csv module with DictWriter.
import csv
rows = [{"name": "A", "score": 90}, {"name": "B", "score": 85}]
with open("scores.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)