Read and write CSV files

Read rows as dicts and write a filtered copy with csv.DictWriter.

python beginner #csv#files#data
プレイグラウンドで開く
python-csv-dictreader.py
import csv
import io

source = io.StringIO("name,score\nada,91\nlinus,78\ngrace,88\n")   # use open("in.csv") for a file
rows = [row for row in csv.DictReader(source) if int(row["score"]) >= 80]

out = io.StringIO()                                                  # use open("out.csv", "w", newline="")
writer = csv.DictWriter(out, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)
print(out.getvalue())