如何将字典保存到文件? [英] How to save a dictionary to a file?
问题描述
我有改变dict值并将dict保存到文本文件中的问题(格式必须相同),我只想更改 member_phone
字段。 / p>
我的文本文件是以下格式:
memberID:member_name: member_email:member_phone
我将文本文件分开:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
b = x [1]
c = x [2]
d = x [3]
e = b +':'+ c +':'+ d
mdict [a] = e
当我尝试更改 member_phone
存储在 d
中,该值已更改不是按键,
def change(mdict,b,c,d,e):
和/或pre
a = input('ID')
如果在mdict中:
d = str '))
mdict [a] = b +':'+ c +':'+ d
else:
print('not')
ow将dict保存到具有相同格式的文本文件?
解决方案Python具有 pickle 模块只是为了这种事情。
这些功能所有这些都需要保存和加载几乎任何对象:
def save_obj(obj,name):
/ pre>
with打开('obj /'+ name +'.pkl','wb')为f:
pickle.dump(obj,f,pickle.HIGHEST_PROTOCOL)
def load_obj(name) :
with open('obj /'+ name +'.pkl','rb')as f:
return pickle.load(f)
请注意pickle.HIGHEST_PROTOCOL是一种二进制格式,不能总是方便,但对性能有好处。协议0是一种文本格式。
为了保存Python的集合,有一个 shelve 模块。
I have problem with changing a dict value and saving the dict to a text file (the format must be same), I only want to change the
member_phone
field.My text file is the following format:
memberID:member_name:member_email:member_phone
and I split the text file with:
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
When I try change the
member_phone
stored ind
, the value has changed not flow by the key,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')
and how to save the dict to a text file with same format?
解决方案Python has the pickle module just for this kind of thing.
These functions are all that you need for saving and loading almost any object:
def save_obj(obj, name ): with open('obj/'+ name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name ): with open('obj/' + name + '.pkl', 'rb') as f: return pickle.load(f)
Note that pickle.HIGHEST_PROTOCOL is a binary format, which could not be always convenient, but is good for performance. Protocol 0 is a text format.
In order to save collections of Python there is the shelve module.
这篇关于如何将字典保存到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!