pickle handling multiple objects ..

Chris Rebert clp2 at rebertia.com
Sun Feb 26 12:58:18 CET 2012


On Sun, Feb 26, 2012 at 3:25 AM, Smiley 4321 <ssmile03 at gmail.com> wrote:
> If I have a sample python code to be executed on Linux. How should  I handle
> multiple objects with 'pickle' as below -
>
> -------
> #!/usr/bin/python
>
> import pickle
>
> #my_list = {'a': 'Apple', 'b': 'Mango', 'c': 'Orange', 'd': 'Pineapple'}
> #my_list = ('Apple', 'Mango', 'Orange', 'Pineapple')
> my_list = ['Apple', 'Mango', 'Orange', 'Pineapple']
> #my_list = ()
> output = open('readfile.pkl', 'wb')
> pickle.dump(my_list, output)
> output.close()
>
> my_file = open('readfile.pkl', 'rb')
> my_list2 = pickle.load(my_file)
> my_file.close()
>
> print my_list
> print my_list2
> -----
>
> This code works fine but now I have to handle multiple objects?

You can either nest the multiple objects inside a single compound
object and just (un)pickle that, or you call call dump()/load()
repeatedly (once per object; yes, this works).

Cheers,
Chris



More information about the Python-list mailing list