Using the pickle module
Q1. Open up the Python interactive shell. Type in
>>>import pickle and then
>>>help(pickle) and then press <ENTER>
What has popped up on the screen?
Q2. Create the following list of data in Python:
myList=['evil pixie', 3.14, 'Tiger', 34254, False]
How many elements has this got? What is the data at myList[2]? Print out the whole list. Print out just element 2.
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.
Can you guess what the access mode will be when we want to read back the file?
Q4. When you have run the above code, open the file called newFile.txt in a text editor such as Notepad in Windows. Describe what you see.
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. Describe what this program does.
Q7. Describe how the pickle.load() method works.
Q8. Do some research. How many data structures can you store in one pickled file structure?
Q9. Do some research. If you wanted to store many data structures in one pickled file, suggest how you might achieve this.
Q10. Create a list of films. Pickle the list. Then get back the pickled list and display the list.