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

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


当前回答

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

其他回答

我还没有计时,但我打赌h5比pickle快;压缩后的文件大小几乎肯定更小。

import deepdish as dd
dd.io.save(filename, {'dict1': dict1, 'dict2': dict2}, compression=('blosc', 9))

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

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模块。

我建议使用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数据。

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