Skip to content

Computer Science · Ch 2 — File Handling in Python

The dump() method

2.8.1

The dump() method

The dump() method is how you write Python objects into a binary file — a process called pickling. Pickling converts a Python object (like a list, dictionary, or number) into a byte stream that can be stored permanently. The file you write to must be opened in binary write mode ("wb"), because the data is being saved as bytes, not as readable text.

The syntax is straightforward:

dump(data_object, file_object)

Here, data_object is the Python object you want to save, and file_object is the file handle returned by open().

Important

You must import the pickle module before using dump(). Without import pickle, Python will not recognise the function.

Program 2-6: Pickling data in Python

import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()

The textbook gives a complete example. First, a list is created: listvalues = [1, "Geetika", 'F', 26] — here 1 is a roll number, "Geetika" a name, 'F' a gender code, and 26 marks. Notice that this list mixes an integer, a string, another string, and another integer — dump() can handle mixed data types in a single object. Then the file "mybinary.dat" is opened in "wb" mode. The pickle.dump() call writes the entire list into that file as a single pickled object. Finally, the file is closed with fileobject.close().

A few practical points to remember:

  • The file extension .dat is conventional but not required — any extension works.
  • If the file does not exist, open() with "wb" will create it. If it already exists, opening in "wb" will overwrite its contents.
  • You can pickle many kinds of Python objects: lists, dictionaries, tuples, sets, numbers, strings, and even custom class instances (though that is beyond this section).
  • Only one object is dumped per dump() call. To store multiple objects, you must call dump() multiple times, once for each object. …