Hi :)

I'm writing a simple program where I need to create multiple lists when i start (from a file) and write them to the file when I quit. I've googled and found that the best way is to put all the lists into a tuple and then write that to the text file. The problem is that i have loooooads of lists...

The lists are all attributes for objects in a class that i have, and I have managed to store all the objects in a list. So basically I have an "objectlist" and each object has it's own list. How do I write all these to a file with pickle? I tried adding "\n" after every list with a for-loop, but well, that didn't really work the way I planned ^^

Help would be much appreciated. Thanks! :)

Here is an example:

use module pickle to dump and load a list object
use binary file modes "wb" and "rb" to make it work with
Python2 and Python3

import pickle

data_str = '''\
Washington DC
Baltimore Maryland
Portland Oregon'''

# make a list of lists
list_lists = []
for line in data_str.split('\n'):

fname = "list_lists.pkl"
# pickle dump the list object
with open(fname, "wb") as fout:
    # default protocol is zero
    # -1 gives highest prototcol and smallest data file size
    pickle.dump(list_lists, fout, protocol=-1)

# pickle load the list object back in (senses protocol)
with open(fname, "rb") as fin:
    list_lists2 = pickle.load(fin)

# visual compare

[['Washington', 'DC'], ['Baltimore', 'Maryland'], ['Portland', 'Oregon']]
[['Washington', 'DC'], ['Baltimore', 'Maryland'], ['Portland', 'Oregon']]
This article has been dead for over six months. Start a new discussion instead.