pickle可以将很多格式的数据保存到一个文件中
以二进制保存。重新加载之后还是之前的格式
用途:
例如当一个列表达到几百行的时候,放到程序里面太难看。可以压缩到一个文件里面
'''
city=[1,2,3,4,5,6,7,8,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7,
1,2,3,4,5,6,7,1,2,3,4,5,6,7 ] #放到这里太难看,而且容易手贱误修改
import pickle
#放到当前文件夹里的city.pkl文件中 wb是以二进制写入
pkl_file=open('city.pkl','wb')
pickle.dump(city,pkl_file)
pkl_file.close()
#保存后上面的程序就可以不用了。当加载时要用以下程序
import pickle
pkl_file=open('city.pkl','rb') #rb 以二进制读取
city=pickle.load(pkl_file)
print(city[1:3])