Basics III 5. Working with files
Working with files
In text processing, you often save data to a file or read it back later.
Write a text file
data = ["apple", "banana", "cherry"]
with open("fruits.txt", "w", encoding="utf-8") as f:
for fruit in data:
f.write(fruit + "\n")
Read a text file
with open("fruits.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(lines)
CSV and JSON
import csv
import json
Use csv.writer, csv.DictReader, json.dump, and json.load when you need structured data.