Python · files

CSV & JSON

Read and write the two most common data files with the csv and json modules.

CSV: reading


          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.

CSV: 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.

CSV: writing


          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.

JSON: reading


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

JSON: writing


          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.

JSON: string conversion


          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 and JSON types

PythonJSON
dictobject { }
list, tuplearray [ ]
strstring "…"
int, floatnumber
True / Falsetrue / false
Nonenull

Exercises

Answer each, then press →.

Exercise 1


        import csv
        # csv.reader returns?
        with open("data.csv") as f:
            reader = csv.reader(f)
            row = next(reader)
        # ans: row is a list
      

Exercise 2


        import csv
        # DictReader first row?
        # ans: first row is headers
      

Exercise 3


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

Exercise 4


        import json
        # load vs loads?
        json.load(file)  # from file
        json.loads(string)  # from string
      

Exercise 5


        import json
        # dump vs dumps?
        json.dump(data, file)  # to file
        json.dumps(data)  # to string
      

Exercise 6


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

Exercise 7


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

Exercise 8


        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.

Exercise 9


        import json
        # can JSON handle tuples?
        json.dumps((1, 2, 3))
        # ans: "[1, 2, 3]" (becomes array)
      
  1. (1, 2, 3)
  2. '[1, 2, 3]'JSON has no tuples; loading it back gives a list

Exercise 10


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

Remember

csv.reader

Rows as lists; DictReader gives dicts keyed by the header line.

csv.writer

writerow one row, writerows many; open with newline="".

load / dump

Read from or write to a file.

loads / dumps

Convert from or to a string.