十七、文件与文件系统
3.序列化与反序列化
Python 的 pickle 模块实现了基本的数据序列和反序列化。
通过 pickle 模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。
通过 pickle 模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
pickle模块中最常用的函数为:
pickle.dump(obj, file, [,protocol]) 将obj对象序列化存入已经打开的file中。
obj:想要序列化的obj对象。
file:文件名称。
protocol:序列化使用的协议。如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。
pickle.load(file) 将file中的对象序列化读出。
file:文件名称。
【例】
import pickle
dataList = [[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no']]
dataDic = {0: [1, 2, 3, 4],
1: ('a', 'b'),
2: {'c': 'yes', 'd': 'no'}}
# 使用dump()将数据序列化到文件中
fw = open(r'.\dataFile.pkl', 'wb')
# Pickle the list using the highest protocol available.
pickle.dump(dataList, fw, -1)
# Pickle dictionary using protocol 0.
pickle.dump(dataDic, fw)
fw.close()
# 使用load()将数据从文件中序列化读出
fr = open('dataFile.pkl', 'rb')
data1 = pickle.load(fr)
print(data1)
data2 = pickle.load(fr)
print(data2)
fr.close()
# [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
# {0: [1, 2, 3, 4], 1: ('a', 'b'), 2: {'c': 'yes', 'd': 'no'}}
练习题
1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
【答】
可以指定的
open(path,encoding = 'utf-8')
2、编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
"""
Input file
test.txt
Output file
['general-purpose,', 'object-oriented,']
"""
def longest_word(filename):
"""
Input file
test.txt
Output file
['general-purpose,', 'object-oriented,']
"""
def longest_word(filename):
with open(filename, 'r', encoding = 'utf-8') as f:
data = f.read().strip().split('\n')
data1 = ' '.join(data).split(' ')
data1.sort(key = lambda x:len(x))
longest = [i for i in data1 if len(i) == len(data1[-1])]
return longest
longest_word('test.txt')
# ['general-purpose,', 'object-oriented,']
参考:
https://blog.csdn.net/XYQLTX/article/details/107875706
https://github.com/datawhalechina/team-learning-program/blob/master/PythonLanguage/17.%20%E6%96%87%E4%BB%B6%E4%B8%8E%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F.md