[Tutor] pickle.load() all dict

Knacktus knacktus at googlemail.com
Sun May 16 11:12:06 CEST 2010


Am 16.05.2010 09:10, schrieb Yutao Deng:
> Hi all:
> I'm trying to learn to use Python  wrote a applet to record every day 
> doing.
> and i use the pickle
> pickle.dump something to file no problem i think.
> but pickle.load whith a problem. can not load all dict do my way that 
> what i pickle.dump().
>
> My code:
> ####
> import cPickle as pickle
> pickle_file = open("data2","rb")
> i = pickle.load(pickle_file)
> print i
> i = pickle.load(pickle_file)
> print i
> i = pickle.load(pickle_file)
> print i
> i = pickle.load(pickle_file)
> print i
> i = pickle.load(pickle_file)
> print i
> ####
> console show :
> {'2010-5-23': ['1242', 'first']}
> {'2010-5-24': ['1232', 'third']}
> {'2010-5-25': ['211', 'second']}
> {'2010-3-22': ['3211', 'fourrrr']}
> {'2050-3-2': ['3990', '322']}
>
> This is i want but that's silly. if the dict too much, then i have not 
> ideas.
>
> the other way from 
> http://mail.python.org/pipermail/tutor/2005-July/039859.html
>
> ####
> import cPickle as pickle
> pickle_file = open("data2","rb")
>
> number_of_pickles = pickle.load(pickle_file)
> for n in range(number_of_pickles):
>     p = pickle.load(pickle_file)
>     print p
> ####
> this way didnt work for me.
>
> console show:
> Traceback (most recent call last):
>     number_of_pickles = pickle.load(pickle_file)
> cPickle.UnpicklingError: invalid load key, '
> '.
> how do i define a range for pickle.load a file . i mean that how can i 
> know how many dict in the data2.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    
If you want to unpickle a file which contains an unknown number of 
pickled objects, this should work. You'll get a list containing all the 
objects.
#############################################################
import cPickle
import pprint

test_data_1 = {"2010-12-13": ["1324", "first"]}
test_data_2 = {"2010-12-14": ["234", "first_and_a_half"]}
test_data_3 = {"2010-12-15": ["132224", "second"]}

for data in (test_data_1, test_data_2, test_data_3):
     with open("data2.pickle", "ab") as file_stream:
         cPickle.dump(data, file_stream, 2)

with open("data2.pickle", "rb") as file_stream:
     pickled_objects = []
     while True:
         try:
             pickled_objects.append(cPickle.load(file_stream))
         except EOFError:
             break

print "Number of pickled objects is %s." % len(pickled_objects)
pprint.pprint(pickled_objects)
############################################################Cheers,

Jan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100516/d86a004b/attachment.html>


More information about the Tutor mailing list