The essentials
A binary file stores data as bytes in the same form as it is held in memory, not as readable characters. Images, audio files and files of Python objects are binary files. To store Python objects such as lists and dictionaries in a file, Python uses the pickle module.
Key points
- Pickling (serialisation): converting a Python object into a byte stream so it can be stored in a file or sent over a network.
- Unpickling (de-serialisation): converting the byte stream back into the original Python object.
- import pickle must be written first.
- pickle.dump(object, file_object): writes (pickles) the object into a file opened in binary write mode.
- variable = pickle.load(file_object): reads one pickled object from a file opened in binary read mode.
- Binary modes add b: 'rb' (read), 'wb' (write, erases old data), 'ab' (append), 'rb+', 'wb+', 'ab+'.
- Each dump() stores one object; each load() reads one object in the same order.
- When load() is called after the last object has been read, it raises EOFError. So reading all records is usually done in a while True loop inside try, with except EOFError to stop.
- To update a record, read all objects, change the required one, and write them back; or use seek() and rewrite.
Exam tips
- The argument order is object first, file second in dump(); load() takes only the file.
- Remember that pickle files are not human-readable when opened in a text editor.
Common mistakes
- Opening a file in 'w' (text) mode and calling pickle.dump(); a binary mode such as 'wb' is required.
- Expecting load() to return all records at once; it returns one object per call.
Practice questions
Log in to answer these questions and see the explanations.Create free accountLog in