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! :)

Recommended Answers

All 2 Replies

You should be able to pickle a list of lists.

Here is an example:

'''pickle_list_lists.py
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'):
    list_lists.append(line.split())

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
print(list_lists)
print('-'*70)
print(list_lists)

'''
[['Washington', 'DC'], ['Baltimore', 'Maryland'], ['Portland', 'Oregon']]
----------------------------------------------------------------------
[['Washington', 'DC'], ['Baltimore', 'Maryland'], ['Portland', 'Oregon']]
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.