Skip to content

File I/O and Persistent Storage ​

Program variables disappear when the program shuts down. That's why you need to save to a file.

python
# Write
with open("data/transactions.jsonl", "a", encoding="utf-8") as f:
    f.write('{"id": "TX-000001", "amount": 15000}\n')

# Read
with open("data/transactions.jsonl", encoding="utf-8") as f:
    for line in f:          # read one line at a time
        print(line.strip())

Key points:

  • "a" mode = append (keeps existing content), "w" mode = rewrite the whole file from scratch
  • encoding="utf-8" is a must (prevents non-English text such as Korean from getting garbled)

Summary ​

ConceptSummary
File I/OA notebook that survives even when the program shuts down

Source: Codyssey-B1/B2-1