Using the pickle module - Answers
Q1. Open up the Python interactive shell. Type in
>>>import pickle and then
>>>help(pickle) and then press <ENTER>
You should see all of the documentation for the pickle module. Although it can be overwhelming for the beginner programmer, students should still know where and how to find the official documentation and should be encouraged to see what is in it.
Q2. Create the following list of data in Python:
myList=['evil pixie', 3.14, 'Tiger', 34254, False]
This list has got five elements. myList[2] is tiger (the first element is at position 0.
Q3. Open a new Python window. At the top of your program, add this line:
import pickle
Now add the following code to your program:
with open('newFile.txt','wb') as fileObject:
pickle.dump(myList,fileObject)
Your program probably looks something like this:
import pickle
myList=['evil pixie', 3.14, 'Tiger', 34254, False]
print(myList[2])
with open('newFile.txt','wb') as fileObject:
pickle.dump(myList,fileObject)
In this code, we opened the file in write binary mode. When we use the pickle module, we want to save in binary mode rather than the text mode we used when using the read and write methods we used before. As always, we will use the with keyword, which automatically closes our file object when we exit the with block.
On the with line, we tell Python to create a file called newFile.txt, to write to it in binary mode and to associate a file object called fileObject with this file. On the pickle.dump line, we tell Python what object we want pickling and what file object to use.
The access mode when we want to read back the file will be rb.
Q4. After opening the file, you should see something like this:
€]q (X evil pixieqG@ ธQ๋…X TigerqMฮ…e.
You can see lots of strange characters because this file is not saved in text mode. It's saved in binary mode.
Q5. Modify your program so that it now looks like the following:
import pickle
myList=['evil pixie', 3.14, 'Tiger', 34254, False]
print(myList)
print('Element 2 is',myList[2])
with open('newFile.txt','wb') as fileObject:
pickle.dump(myList,fileObject)
with open('newFile.txt','rb') as fileObject:
myNewList = pickle.load(fileObject)
print(myNewList)
Q6. This program creates a list, prints it out and element 2. It then pickles and unpickles the list and prints it out again.
Q7. The pickle.load() method works by loading a file from the file object we have already opened in read binary mode. Here, we have assigned a variable called myNewList to the loaded file.
Q8. You can store in one data structure per pickled file.
Q9. You could put lots of different data structures in a list, then save that list in a pickled file.
Q10. To create a list of films:
import pickle
myFilms=['Dune','Lord of the rings','Terminator','The Hobbit']
print(myFilms)
with open('filmFile.txt','wb') as fileObject:
pickle.dump(myFilms,fileObject)
with open('filmFile.txt','rb') as fileObject:
myNewFilmList = pickle.load(fileObject)
print(myNewFilmList)