PyForge ยท Python practice library
All topics

Topic 11 of 17

File I/O

Read and write text, JSON, and CSV files safely.

open() & with
Read/write modes
JSON
CSV

Basic

2 programs

Program 1

Write to a file

Basic

Create and write text to a file.

python
with open("notes.txt", "w") as f:
    f.write("Python is fun!
")
    f.write("Keep practicing.
")

Program 2

Read a file line by line

Basic

Iterate over file lines.

python
with open("notes.txt") as f:
    for line in f:
        print(line.strip())

Intermediate

1 program

Program 1

Work with JSON

Intermediate

Serialize Python dicts to JSON.

python
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)

Advanced

1 program

Program 1

CSV read/write

Advanced

Use the csv module with DictWriter.

python
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)