我有一个问题,改变dict值和保存dict到一个文本文件(格式必须相同),我只想改变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')

如何将字典保存为相同格式的文本文件?


当前回答

file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

或者使用上下文管理器,这更好:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

其他回答

对于字符串字典(例如您正在处理的字符串字典),只能使用Python内置的文本处理功能来完成。

(注意,如果值是其他值,这将不起作用。)

with open('members.txt') as file:
    mdict={}
    for line in file:
        a, b, c, d = line.strip().split(':')
        mdict[a] = b + ':' + c + ':' + d

a = input('ID: ')
if a not in mdict:
    print('ID {} not found'.format(a))
else:
    b, c, d = mdict[a].split(':')
    d = input('phone: ')
    mdict[a] = b + ':' + c + ':' + d  # update entry
    with open('members.txt', 'w') as file:  # rewrite file
        for id, values in mdict.items():
            file.write(':'.join([id] + values.split(':')) + '\n')
file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

或者使用上下文管理器,这更好:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

我不知道你的第一个问题是什么,但如果你想保存一个字典到文件,你应该使用json库。查找加载和放置函数的文档。

Python有pickle模块专门用于这种事情。

这些函数是保存和加载几乎任何对象所需要的全部:

import pickle 

with open('saved_dictionary.pkl', 'wb') as f:
    pickle.dump(dictionary, f)
        
with open('saved_dictionary.pkl', 'rb') as f:
    loaded_dict = pickle.load(f)

为了保存Python的集合,有shelve模块。

我喜欢使用漂亮的打印模块以非常友好的可读形式存储字典:

import pprint

def store_dict(fname, dic):
    with open(fname, "w") as f:
        f.write(pprint.pformat(dic, indent=4, sort_dicts=False))
        # note some of the defaults are: indent=1, sort_dicts=True

然后,在恢复时,读入文本文件并eval()它将字符串转换回dict:

def load_file(fname):
    try:
        with open(fname, "r") as f:
            dic = eval(f.read())
    except:
        dic = {}
    return dic