Python - 将Python对象写入文件
使用Python自带的shelve
模块
写入
import shelve
'''
将对象写入文件
'''
# 使用shelve打开文件
file = shelve.open('test')
# 要保存的对象
data = {'John': '001', 'Kate': '002', 'Harry': '003'}
# 键
data_key = 'names'
# 在file中保存一个键值对
# key - data_key
# value - data对象
file[data_key] = data
# 关闭文件
file.close()
可以看到生成了三个文件
文件详情
.dat
不能看.dir
和.bak
都保存了键值对相关信息
读取
import shelve
'''
读取对象
'''
# 使用shelve打开文件
file = shelve.open('test')
# 指定键
data_key = 'names'
# 读取对应的对象
data = file[data_key]
# 关闭文件
file.close()
# 输出
print(data)
输出结果
{'John': '001', 'Kate': '002', 'Harry': '003'}
完成!
参考:https://www.cnblogs.com/qy-blogs/p/9955316.html