Δημοσιεύτηκε: 30 Σεπ 2011, 10:23
Ορίστε για python3.x:
Αυτό δουλεύει σε 3.x και 2.x:
Βασικά θα πρέπει να διαλέξεις, ή python3 χωρίς gui (μιλάω για το gtk, υπάρχει το Qt ή άλλα) ή python2 με gtk.
- Κώδικας: Επιλογή όλων
#!/usr/bin/python3
import os.path
import pprint # "Pretty print"
try:
import cPickle as pickle
except ImportError:
import pickle
pickle_file = "cache3.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, "rb") 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, "wb") as f:
pickle.dump(pickle_dict, f)
Αυτό δουλεύει σε 3.x και 2.x:
- Κώδικας: Επιλογή όλων
#!/usr/bin/python
import os.path
import pprint # "Pretty print"
try:
import cPickle as pickle
except ImportError:
import pickle
pickle_file = "cache2_3.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, "rb") 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, "wb") as f:
pickle.dump(pickle_dict, f, protocol=0)
Βασικά θα πρέπει να διαλέξεις, ή python3 χωρίς gui (μιλάω για το gtk, υπάρχει το Qt ή άλλα) ή python2 με gtk.