Read and write the two most common data files with the csv and json modules.
import csv
# read CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# ans: row is a list
Each line of the file becomes one list of strings, split at the commas.
DictReader
import csv
# read with headers
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["age"])
The first line supplies the keys; every later line becomes a dict.
import csv
# write CSV
data = [["Name", "Age"], ["Alice", 25]]
with open("out.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Each inner list becomes one line, with the values joined by commas.
import json
# read JSON file
with open("data.json", "r") as file:
data = json.load(file)
# ans: returns dict or list
import json
# write JSON file
data = {"name": "Alice", "age": 25}
with open("out.json", "w") as file:
json.dump(data, file, indent=2)
indent=2 puts each item on its own line, indented two spaces.
import json
# to JSON string
data = {"name": "Alice"}
json_str = json.dumps(data)
# ans: '{"name": "Alice"}'
# from JSON string
data = json.loads(json_str)
# ans: {"name": "Alice"}
The s in dumps / loads stands for string.
| Python | JSON |
|---|---|
| dict | object { } |
| list, tuple | array [ ] |
| str | string "…" |
| int, float | number |
| True / False | true / false |
| None | null |
Answer each, then press →.
import csv
# csv.reader returns?
with open("data.csv") as f:
reader = csv.reader(f)
row = next(reader)
# ans: row is a list
import csv
# DictReader first row?
# ans: first row is headers
import csv
# writerows vs writerow?
writer.writerows([[1,2],[3,4]])
# ans: writes 2 rows
writer.writerow([1,2])
# ans: writes 1 row
import json
# load vs loads?
json.load(file) # from file
json.loads(string) # from string
import json
# dump vs dumps?
json.dump(data, file) # to file
json.dumps(data) # to string
import json
# indent parameter?
json.dumps({"a": 1}, indent=2)
# ans: pretty-printed with 2 spaces
{
"a": 1
}
import json
# JSON with Python types?
json.dumps([1, "text", True, None])
# ans: '[1, "text", true, null]'
import csv
# newline="" why?
open("file.csv", "w", newline="")
# ans: prevents extra blank lines
The csv writer ends rows with its own line endings; without newline="", Windows adds a second one.
import json
# can JSON handle tuples?
json.dumps((1, 2, 3))
# ans: "[1, 2, 3]" (becomes array)
import csv
# CSV delimiter?
csv.reader(file, delimiter=";")
# ans: use semicolon instead of comma
csv.readerRows as lists; DictReader gives dicts keyed by the header line.
csv.writerwriterow one row, writerows many; open with newline="".
load / dumpRead from or write to a file.
loads / dumpsConvert from or to a string.