如何将字典保存到文件中?
如何将字典保存到文件中?
我遇到了一个问题:我要修改一个字典的值并保存到一个文本文件中(文件格式必须相同),我只想修改 member_phone
字段。
我的文本文件格式如下:
memberID:member_name:member_email:member_phone
我是通过以下方式分割文本文件的:
mdict={} for line in file: x=line.split(':') a=x[0] b=x[1] c=x[2] d=x[3] e=b+':'+c+':'+d mdict[a]=e
当我尝试改变存储在 d
中的 member_phone
值时,这个值并没有通过键流动而被改变了。
def change(mdict,b,c,d,e): a=input('ID') if a in mdict: d= str(input('phone')) mdict[a]=b+':'+c+':'+d else: print('not')
我该如何以相同的格式将字典保存到文本文件中?
admin 更改状态以发布 2023年5月20日
Pickle可能是最好的选择,但如果有人想知道如何使用NumPy将字典保存和加载到文件中:
import numpy as np # Save dictionary = {'hello':'world'} np.save('my_file.npy', dictionary) # Load read_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item() print(read_dictionary['hello']) # displays "world"
顺便说一下:NPY文件查看器