知识点总结:
- 对象持久化(通过序列化实现)
- str - bytes - bytearray
扁平序列化
生成data.txt文本文件
scores = [99, 88, 77, 5, 4, 3]
def write_scores():
"""会在当前脚本文件同级目录下生成data.txt文件,并以str形式写入scores"""
with open('data.txt', 'w', encoding='utf8') as f:
f.write(str(scores))
f.flush()
f.close()
def read_scores():
"""通过eval()函数将读取的str转为list类型"""
with open('data.txt', 'r', encoding='utf8') as f:
lst = eval(f.read())
print(type(lst))
print(lst)
if __name__ == '__main__':
read_scores()
# 输出
<class 'bytes'>
b'\x80\x03]q\x00(KcKXKMK\x05K\x04K\x03e.'
通过pickle转为str序列化
import pickle
scores = [99, 88, 77, 5, 4, 3]
def write_scores():
"""通过pickle直接将对象序列化"""
with open('data.txt', 'w', encoding='utf8') as f:
f.write(str(pickle.dumps(scores)))
f.flush()
f.close()
def read_scores():
"""通过pickle直接将对象反序列化"""
with open('data.txt', 'r', encoding='utf8') as f:
lst = pickle.loads(eval(f.read()))
print(type(lst))
print(lst)
if __name__ == '__main__':
write_scores()
read_scores()
# 输出
<class 'list'>
[99, 88, 77, 5, 4, 3]
通过pickle直接将对象序列化
生成pickle.db二进制文件
import pickle
scores = [99, 88, 77, 5, 4, 3]
def write_scores():
pickle.dump(scores, open('pickle.db', 'wb'))
def read_scores():
lst = pickle.load(open('pickle.db', 'rb'))
print(type(lst))
print(lst)
if __name__ == '__main__':
write_scores()
read_scores()
通过shelve序列化
生成存储文件
shelve.student.bak
shelve.student.dat
shelve.student.dir
import pickle
import shelve
scores = [99, 88, 77, 5, 4, 3]
student = {'name':'Tom','age':20}
def write_scores():
db = shelve.open('shelve.student')
db['stu'] = student
db['scores'] = scores
def read_scores():
db = shelve.open('shelve.student')
print(len(db))
temp_stu = db['stu']
print(type(temp_stu))
print(temp_stu)
temp_scores = db['scores']
print(type(temp_scores))
print(temp_scores)
del db['stu']
print(db['stu'])
if __name__ == '__main__':
write_scores()
read_scores()
# 输出
2
<class 'dict'>
{'name': 'Tom', 'age': 20}
<class 'list'>
[99, 88, 77, 5, 4, 3]
Traceback (most recent call last):
File "C:\Users\u6072479\AppData\Local\Programs\Python\Python36\lib\shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'stu'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/u6072479/PycharmProjects/numpy-practice/20191127/main.py", line 31, in <module>
read_scores()
File "C:/Users/u6072479/PycharmProjects/numpy-practice/20191127/main.py", line 26, in read_scores
print(db['stu'])
File "C:\Users\u6072479\AppData\Local\Programs\Python\Python36\lib\shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "C:\Users\u6072479\AppData\Local\Programs\Python\Python36\lib\dbm\dumb.py", line 148, in __getitem__
pos, siz = self._index[key] # may raise KeyError
KeyError: b'stu'
Process finished with exit code 1
字符串本质
>>> s1 = 'ABC'
>>> s1.encode('ASCII')
b'ABC'
>>> s2 = 'Python基础'
>>> s2.encode('ASCII')
# ASCII不支持汉字
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-7: ordinal not in range(128)
>>> s2.encode('utf8')
b'Python\xe5\x9f\xba\xe7\xa1\x80'
>>> s3 = '即'
# utf8编码一个汉字
>>> s3.encode('UTF8')
b'\xe5\x8d\xb3'
# utf16编码一个汉字
>>> s3.encode('UTF16')
b'\xff\xfesS'
>>> b1 = b'\xe5\x8d\xb3'
# 解码回str
>>> b1.decode('utf8')
'即'