1、多次存储和提取
import pickle class Cat: ''' The object of cat ''' head = "head" body = "body" foot = "foot" # initial the cat def __init__(self, head='0', body='1', foot='2'): self.head = head self.body = body self.foot = foot if __name__ == '__main__': file_path = 'D:/tmp.pk' # Save objects write_file = open(file_path, 'wb') # The number of 'dump' must be equal the number of 'load' pickle.dump(Cat(1, 2, 3), write_file) pickle.dump(Cat(4, 5, 6), write_file) write_file.close() read_file = open(file_path, 'rb') cat = pickle.load(read_file) print(str(cat.head) + " " + str(cat.body) + " " + str(cat.foot)) cat = pickle.load(read_file) print(str(cat.head) + " " + str(cat.body) + " " + str(cat.foot)) read_file.close()
2、列表存取
import pickle class Cat: ''' The object of cat ''' head = "head" body = "body" foot = "foot" # initial the cat def __init__(self, head='0', body='1', foot='2'): self.head = head self.body = body self.foot = foot def open_pickle_file(file_path): ''' Open the file of bin :param file_path: path of file :return: ''' with open(file_path, 'rb') as f: data = pickle.load(f) return data return 0 def save_pickle_file(data, file_path): ''' Save the file of data :param data: The data of input :param file_path: The path of file :return: ''' with open(file_path, 'wb') as f: pickle.dump(data, f) return 0 if __name__ == '__main__': file_path = 'D:/tmp.pk' data = list() data.append(Cat(1, 2, 3)) data.append(Cat(4, 5, 6)) # Save list save_pickle_file(data, file_path) cats = open_pickle_file(file_path) print(str(cats[0].head)+" "+str(cats[0].body)+" "+str(cats[0].foot)) print(str(cats[1].head) + " " + str(cats[1].body) + " " + str(cats[1].foot))