REVISED: Sunday, March 3, 2013
Python 3 "Pickle".
I. PYTHON 3 "PICKLE" INTRODUCTION
In Python to “pickle”, refers to a type of file input output (I/O) where you save a Python object to a file. Pickling stores objects on your hard drive instead of in your random access memory (RAM), short term memory, where the objects will be lost when you log out.
You can only pickle one object into one file.
First, you have to import the Python "pickle module", e.g., import pickle. We need the Python “pickle module” to get the "pickle dump" function to dump the object we want to pickle into the file; e.g., pickle.dump(). Later we can use the Python "pickle module" "pickle load" function to un-pickle the object by pulling the object from the file; e.g., pickle.load().
Second, you have to create a file output “file object” using the Python “open method”; e.g., outFile = open(‘pickleExample.txt’, ‘wb’), which we open in binary mode; e.g., ‘wb’ for write binary. I am using a text file named pickleExample; however, you can use any file name you prefer. I used outFile for the "file object"; however, any "file object" name can be used.
Third, you have to create a file input “file object” using the Python “open method”; e.g., inFile = open(‘pickleExample.txt’, ‘rb’), which we open in binary mode; e.g., ‘rb’ for read binary. I am still using the original text file named pickleExample; you must use your original file name because that is the one you wrote to. I used inFile for the "file object"; however, any "file object" name can be used.
II. PYTHON 3 PICKLE EXAMPLE SOURCE CODE
import pickle
def main():
# Creating objects we want to pickle, write, to a file.
pickleObjects = ["home", "library", "garage", "garden", "pool", "car"]
print (pickleObjects)
# Pickling, writing, to a file.
outFile = open('pickleExample.txt', 'wb')
pickle.dump(pickleObjects, outFile)
outFile.close()
# Un-pickling, reading, from a file.
inFile = open('pickleExample.txt', 'rb')
unPickledObjects = pickle.load(inFile)
print (unPickledObjects)
inFile.close()
if __name__ == '__main__':
main()
III. PYTHON 3 PICKLE EXAMPLE OUTPUT
>>>
['home', 'library', 'garage', 'garden', 'pool', 'car']
['home', 'library', 'garage', 'garden', 'pool', 'car']
>>>
['home', 'library', 'garage', 'garden', 'pool', 'car']
['home', 'library', 'garage', 'garden', 'pool', 'car']
>>>
IV. REFERENCES
The Python Tutorial by Guido van Rossum and Fred L. Drake, Jr., editor (2003)
Style Guide for Python Code by Guido van Rossum and Barry Warsaw (2001)
Enjoy Python 3 "Pickle".
Elcric Otto Circle
-->
-->
-->
How to Link to My Home Page
It will appear on your website as:"Link to: ELCRIC OTTO CIRCLE's Home Page"
No comments:
Post a Comment