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.
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.
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.
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.
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."] >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With