[Tutor] pickling, writing, reading individual lists from a file

Dinesh B Vadhia dineshbvadhia at hotmail.com
Mon Nov 3 08:20:47 CET 2008


I want to pickle a bunch of lists and write each list separately to a fileand then read them back.  Here is my code with the EOF error:

import cPickle as pickle

m = [[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14]]

filename = 'lists.txt'
fw = open(filename, 'w')
for l in m:
        n = pickle.dumps(l, 2) + "\n"
        fw.write(n)
fw.close()

fr = open(filename, 'r')
for line in fr:
        line = line.rstrip("\n")
        line = pickle.loads(line)
        print line
fr.close()

Traceback (most recent call last):
  File "....py", line 61, in <module>
    line = pickle.loads(line)
EOFError

If I change the read file code to:

lines = fr.readlines()
print lines
for line in lines:
        line = line.rstrip("\n")
        line = pickle.loads(line)
        print line
fr.close()

The error message is:

['\x80\x02]q\x01(K\x01K\x02K\x03K\x04e.\n', '\x80\x02]q\x01(K\x05K\x06K\x07K\x08K\tK\n', 'e.\n', '\x80\x02]q\x01(K\x0bK\x0cK\rK\x0ee.\n']
[1, 2, 3, 4]

Traceback (most recent call last):
  File "....py", line 73, in <module>
    line = pickle.loads(line)
EOFError

Note how the list lines contains 4 elements instead of 3.  

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081102/67913032/attachment.htm>


More information about the Tutor mailing list