使用 Pickle 進行序列化
這是一個展示泡菜基本用法的例子 : - ****
# Importing pickle
try:
import cPickle as pickle # Python 2
except ImportError:
import pickle # Python 3
# Creating Pythonic object:
class Family(object):
def __init__(self, names):
self.sons = names
def __str__(self):
return ' '.join(self.sons)
my_family = Family(['John', 'David'])
# Dumping to string
pickle_data = pickle.dumps(my_family, pickle.HIGHEST_PROTOCOL)
# Dumping to file
with open('family.p', 'w') as pickle_file:
pickle.dump(families, pickle_file, pickle.HIGHEST_PROTOCOL)
# Loading from string
my_family = pickle.loads(pickle_data)
# Loading from file
with open('family.p', 'r') as pickle_file:
my_family = pickle.load(pickle_file)
有關 Pickle 的詳細資訊,請參閱 Pickle。
警告 :pickle 的官方文件清楚地表明沒有安全保證。不要載入任何不信任其來源的資料。