Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump a list in a pickle file and retrieve it back later [closed]

I'm trying to save a list of strings, so that it can be accessed later. How can it be achieved using pickle? An illustrative example could help.

like image 210
Lewis Avatar asked Aug 23 '14 16:08

Lewis


People also ask

Does pickle load close file?

You then open the pickle file for reading, load the content into a new variable, and close up the file. Loading is done through the pickle. load() method.

How do you dump files in pickle?

Python Pickle dump To do so, we have to import the pickle module first. Then use pickle. dump() function to store the object data to the file. pickle.

How do I read a pickle file?

load you should be reading the first object serialized into the file (not the last one as you've written). After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle. load again, it will read that next object - do that until the end of the file.


Video Answer


1 Answers

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51)  [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."] >>>  >>> import pickle >>>  >>> with open('parrot.pkl', 'wb') as f: ...   pickle.dump(mylist, f) ...  >>>  

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51)  [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> with open('parrot.pkl', 'rb') as f: ...   mynewlist = pickle.load(f) ...  >>> mynewlist ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."] >>> 
like image 84
Mike McKerns Avatar answered Oct 05 '22 04:10

Mike McKerns