Δημοσιεύτηκε: 29 Σεπ 2011, 15:22
από medigeek
Ορίστε ένα παράδειγμα με dictionaries και pickle που δουλεύει:
Κώδικας: Επιλογή όλων
#!/usr/bin/python
import os.path
import pprint # "Pretty print"
try:
import cPickle as pickle
except ImportError:
import pickle

pickle_file = "cache.db"
pickle_dict = dict()

# If pickle file exists
if os.path.exists(pickle_file):
#Use pickle file
print("Found pickle file, loading dictionary")
with open(pickle_file, "r") as f:
pickle_dict = pickle.load(f)
else:
print("Did not find pickle file, creating default dictionary")
pickle_dict = {
"my1stkey": "my1stvalue",
"my2ndkey": "my2ndvalue",
}

print("Current dictionary")
pprint.pprint(pickle_dict)

print("Adding to dictionary")
pickle_dict["newkey"] = "newvalue"
pickle_dict["otherkey"] = "othervalue"
pprint.pprint(pickle_dict)

print("Remove from otherkey from dictionary")
pickle_dict.pop("otherkey")
# Same as: del pickle_dict["otherkey"]
# newkey is still there!
pprint.pprint(pickle_dict)

# When done processing, write back to file through pickle
print("Will save this dictionary:")
pprint.pprint(pickle_dict)
with open(pickle_file, "w") as f:
pickle.dump(pickle_dict, f)


Την πρώτη φορά που το τρέχεις:
- θα δημιουργήσει ένα default dictionary
- θα προσθέσει τα keys "otherkey" και "newkey"
- θα αφαιρέσει το "otherkey"
- θα αποθηκεύσει το dictionary στο αρχείο cache.db

Τη δεύτερη φορά θα βρει το αποθηκευμένο αρχείο pickle και θα το χρησιμοποιήσει (Πρόσεξε ότι τώρα υπάρχει το "newkey").