使用pickle
这个包,注意pkl是一个二进制文件,因此写入和读取的时候都需要使用wb
或rb
案例
import pickle
def write_pkl(write_data, pkl_path): # 写入pkl
pickle.dump(write_data, open(pkl_path, 'wb'))
def read_pkl(pkl_file): # 读取pkl
my_data = pickle.load(open(pkl_file, 'rb'))
return my_data
if __name__ == '__main__':
path = 'dict_data.pkl'
data = ['1234', 123, 4, {'1': 3}]
# 写入pkl文件
write_pkl(data, path)
# 读取pkl文件
read_pkl_content = read_pkl(path)
print(read_pkl_content)