我有一个问题,改变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')

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


当前回答

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

其他回答

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)

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文件查看器

对于字符串字典(例如您正在处理的字符串字典),只能使用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')

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

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

由于Pickle有一些安全问题,并且速度较慢(来源),我将选择JSON,因为它快速,内置,人类可读,并且可互换:

import json
data = {'another_dict': {'a': 0, 'b': 1}, 'a_list': [0, 1, 2, 3]}
# e.g. file = './data.json' 
with open(file, 'w') as f: 
    json.dump(data, f)

阅读也很简单:

with open(file, 'r') as f:
    data = json.load(f)

这类似于这个答案,但是正确地实现了文件处理。

如果性能改进仍然不够,我强烈推荐orjson,快速,正确的JSON库,用于Rust之上的Python构建。