CSV & JSON

CSV - Reading

  1. import csv
  2. # read CSV
  3. with open("data.csv", "r") as file:
  4. reader = csv.reader(file)
  5. for row in reader:
  6. print(row)
  7. #ans: row is a list

CSV - DictReader

  1. import csv
  2. # read with headers
  3. with open("data.csv", "r") as file:
  4. reader = csv.DictReader(file)
  5. for row in reader:
  6. print(row["name"], row["age"])

CSV - Writing

  1. import csv
  2. # write CSV
  3. data = [["Name", "Age"], ["Alice", 25]]
  4. with open("out.csv", "w", newline="") as file:
  5. writer = csv.writer(file)
  6. writer.writerows(data)

JSON - Reading

  1. import json
  2. # read JSON file
  3. with open("data.json", "r") as file:
  4. data = json.load(file)
  5. #ans: returns dict or list

JSON - Writing

  1. import json
  2. # write JSON file
  3. data = {"name": "Alice", "age": 25}
  4. with open("out.json", "w") as file:
  5. json.dump(data, file, indent=2)

JSON - String Conversion

  1. import json
  2. # to JSON string
  3. data = {"name": "Alice"}
  4. json_str = json.dumps(data)
  5. #ans: '{"name": "Alice"}'
  6. #ans: from JSON string
  7. data = json.loads(json_str)
  8. #ans: {"name": "Alice"}

Exercises - Part 1

  1. import csv
  2. # csv.reader returns?
  3. with open("data.csv") as f:
  4. reader = csv.reader(f)
  5. row = next(reader)
  6. #ans: row is a list

Exercises - Part 2

  1. import csv
  2. # DictReader first row?
  3. #ans: first row is headers

Exercises - Part 3

  1. import csv
  2. # writerows vs writerow?
  3. writer.writerows([[1,2],[3,4]])
  4. #ans: writes 2 rows
  5. writer.writerow([1,2])
  6. #ans: writes 1 row

Exercises - Part 4

  1. import json
  2. # load vs loads?
  3. json.load(file) # from file
  4. json.loads(string) # from string

Exercises - Part 5

  1. import json
  2. # dump vs dumps?
  3. json.dump(data, file) # to file
  4. json.dumps(data) # to string

Exercises - Part 6

  1. import json
  2. # indent parameter?
  3. json.dumps({"a": 1}, indent=2)
  4. #ans: pretty-printed with 2 spaces

Exercises - Part 7

  1. import json
  2. # JSON with Python types?
  3. json.dumps([1, "text", True, None])
  4. #ans: '[1, "text", true, null]'

Exercises - Part 8

  1. import csv
  2. # newline="" why?
  3. open("file.csv", "w", newline="")
  4. #ans: prevents extra blank lines

Exercises - Part 9

  1. import json
  2. # can JSON handle tuples?
  3. json.dumps((1, 2, 3))
  4. #ans: "[1, 2, 3]" (becomes array)

Exercises - Part 10

  1. import csv
  2. # CSV delimiter?
  3. csv.reader(file, delimiter=";")
  4. #ans: use semicolon instead of comma

Google tag (gtag.js)