1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# -*- coding: utf-8 -*- __author__ = 'songhao' import pickle shoplistfile = 'shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = open(shoplistfile, 'wb') #以二进制的方式进行写入 pickle.dump(shoplist, f) # dump the object to a file 倒入一个文件,存入 f.close() del shoplist # remove the shoplist # Read back from the storage f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # 读入文件 print(storedlist) dump: 写入 load: 读取 |
对于序列化最普遍的做法就是使用 pickle 模块。为了将一个对象保存到一个文件中,可以这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import pickle data = ... # Some Python object f = open('somefile', 'wb') pickle.dump(data, f) 为了将一个对象转储为一个字符串,可以使用 pickle.dumps() : s = pickle.dumps(data) 为了从字节流中恢复一个对象,使用 picle.load() 或 pickle.loads() 函数。比如: # Restore from a file f = open('somefile', 'rb') data = pickle.load(f) # Restore from a string 将一个字符串恢复成对象 data = pickle.loads(s) |
