- If you use lists to store the data from your program, there is a neat function called pickle() that can be used to save the entire list rather than using loops
- The example below saves a list to a file and then reloads it
- The data is not stored as text though, so you can’t edit it by hand
- You need to declare the pickle library at the start of your program
#Import pickle library
import pickle
#List held in program
address_list = [
['Ken McCall', '65 Lincoln Blvd', 'Washington', '07989 345664'],
['Joe Smith', '21 Jefferson Ave', 'Washington', '07664 354748'],
['Ally Major', '99 Kennedy St', 'Washington', '08775 467362'],
['Jay Jones', '57 3rd St', 'Delaware', '08556 474562']
]
#Open file for write (binary), save list to file and close
file = open('savedfile.dat','wb')
pickle.dump(address_list,file)
file.close()
#Clear the address list
address_list.clear()
#Open file for reading (binary), read back into list and close
file = open('savedfile.dat','rb')
address_list = pickle.load(file)
file.close
#Print list contents
print(address_list)
Tasks
- Type in the code and make sure it works
- Open the .dat file in notepad. What do you see?
- Save and label your code
Extension Task
You cannot create pickle data files using notepad, so you need to build code to generate a list that you then save to the file. From that point on you need to read into your list at the start of the program, and save it back out at the end. Removing the list declaration at the top, and swapping round the read and write sections in the program above will make sure your program does this properly