Programs need to store whole objects such as lists and dictionaries, and exchange tables of data with other software. Pickle, CSV and JSON handle these needs.

The pickle Module

The pickle module converts a Python object into a stream of bytes, a process called pickling or serialisation, and back again, called unpickling. pickle.dump(obj, file) writes an object to a binary file, and pickle.load(file) reads it back. Lists, dictionaries, tuples and many other objects can be stored in this way. Only load pickle files that come from a trusted source, because unpickling can run harmful code.

Definition: Pickling. Converting a Python object into a byte stream that can be stored in a file and later restored by unpickling.

CSV Files

A CSV (comma separated values) file stores a table as text, with one row per line and the values separated by commas. The csv module provides csv.writer() and csv.reader(), and csv.DictWriter and csv.DictReader to work with column names. A file is opened with newline="" when writing, so that no blank lines appear on some systems. All values read from a CSV file are strings and must be converted when numbers are needed.

JSON Files

JSON (JavaScript Object Notation) is a text format of key-value pairs and lists that is used widely by web services. The json module has json.dump(obj, file) and json.load(file) for files, and json.dumps(obj) and json.loads(text) for strings. A Python dictionary maps naturally to a JSON object and a list to a JSON array. Unlike pickle, JSON is readable by people and by programs in other languages.

Table 3.5: Pickle, CSV and JSON compared

Feature pickle CSV JSON
Form Binary Text Text
Stores Python objects Tables Nested data
Readable by people No Yes Yes
Other languages No Yes Yes

Example 3.5: Saving data in three formats

Problem: Store the dictionary {"name": "Asha", "marks": [72, 85]} with pickle and JSON, and write two rows of a table to a CSV file and read them back.

Solution:

  1. Use pickle.dump with a "wb" file and pickle.load with "rb".
  2. Use json.dump and json.load with text files.
  3. Use csv.writer with writerow, then csv.reader to read.

Result: All three give back the same data, and the CSV values are returned as strings.

import pickle, json, csv
d = {"name": "Asha", "marks": [72, 85]}
with open("d.pkl", "wb") as f:
    pickle.dump(d, f)
with open("d.pkl", "rb") as f:
    print(pickle.load(f))
with open("d.json", "w") as f:
    json.dump(d, f)
print(open("d.json").read())
with open("t.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["roll", "marks"])
    w.writerow([1, 72])
with open("t.csv") as f:
    print(list(csv.reader(f)))

Output

{'name': 'Asha', 'marks': [72, 85]}
{"name": "Asha", "marks": [72, 85]}
[['roll', 'marks'], ['1', '72']]

Common mistakes

  • Opening a pickle file in text mode instead of binary mode.
  • Treating numbers read from a CSV file as numbers. They are strings.
  • Loading a pickle file from an unknown source.

Key takeaways

  • pickle.dump and pickle.load store and restore Python objects in binary files.
  • csv.writer and csv.reader handle table data.
  • json.dump and json.load handle nested data in text.
  • Values read from CSV are strings.

Practice questions

  1. What does pickle.dump do?
  2. What type are the values read from a CSV file?
  3. Which Python type corresponds to a JSON object?

Answers to the practice questions

  1. Writes a Python object to a binary file.
  2. Strings.
  3. A dictionary.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit III