import shelve
# 给文件写入一个字典:{'key':{'int':10, 'float':9.5, 'string':'Sample data'}}
f = shelve.open('shelve_file')
f['key'] = {'int': 10, 'float': 9.5, 'string': 'Sample data'}  # 直接对文件句柄操作,就可以存入数据
f.close()

f = shelve.open('shelve_file')
print(f['key'])
f.close()

# 给字典添加键值对{'int': 10, 'float': 9.5, 'string': 'Sample data', 'new_value': 'this was not here before'}
f1 = shelve.open('shelve_file', writeback=True)
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()
f1 = shelve.open('shelve_file')
print(f1['key'])
f1.close()
# writeback=True 如果相对shelve文件进行修改,必须要添加这个参数

 

相关文章:

  • 2021-07-26
  • 2022-01-27
  • 2021-11-12
  • 2021-12-10
  • 2019-03-12
  • 2021-08-20
  • 2021-07-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-21
  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
相关资源
相似解决方案