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

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


当前回答

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

其他回答

我不知道你的第一个问题是什么,但如果你想保存一个字典到文件,你应该使用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文件查看器

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

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

我建议使用JSON格式而不是pickle格式保存数据,因为JSON的文件是人类可读的,这使得您的调试更容易,因为您的数据很小。JSON文件也被其他程序用来读取和写入数据。你可以在这里阅读更多信息

你需要安装JSON模块,你可以用pip:

pip install json


# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )

这将创建一个名为myfile的json文件。

# To read data from file:
data = json.load( open( "myfile.json" ) )

读取并存储myfile。数据对象中的Json数据。