Python 如何将字典保存到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19201290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save a dictionary to a file?
提问by XueYuan Wang
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.
我在更改字典值并将字典保存到文本文件(格式必须相同)时遇到问题,我只想更改member_phone
字段。
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 in d
, the value has changed not flow by the key,
当我尝试更改member_phone
存储在 中时d
,值已更改而不是按键流动,
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?
以及如何将dict保存到具有相同格式的文本文件中?
回答by John
I'm not sure what your first question is, but if you want to save a dictionary to file you should use the json
library. Look up the documentation of the loads and puts functions.
我不确定您的第一个问题是什么,但是如果您想将字典保存到文件中,您应该使用该json
库。查找负载和放置函数的文档。
回答by Zah
Python has the picklemodule 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)
These functions assume that you have an obj
folder in your current working directory, which will be used to store the objects.
这些函数假设您obj
在当前工作目录中有一个文件夹,用于存储对象。
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.
请注意,这pickle.HIGHEST_PROTOCOL
是一种二进制格式,这并不总是很方便,但对性能有好处。协议0
是一种文本格式。
In order to save collections of Python there is the shelvemodule.
为了保存 Python 的集合,有搁置模块。
回答by mguijarr
Unless you really want to keep the dictionary, I think the best solution is to use the csv
Python module to read the file.
Then, you get rows of data and you can change member_phone
or whatever you want ;
finally, you can use the csv
module again to save the file in the same format
as you opened it.
除非你真的想保留字典,否则我认为最好的解决方案是使用csv
Python模块读取文件。然后,您获得数据行,您可以进行更改member_phone
或进行任何您想要的操作;最后,您可以csv
再次使用该模块以与打开时相同的格式保存文件。
Code for reading:
阅读代码:
import csv
with open("my_input_file.txt", "r") as f:
reader = csv.reader(f, delimiter=":")
lines = list(reader)
Code for writing:
编写代码:
with open("my_output_file.txt", "w") as f:
writer = csv.writer(f, delimiter=":")
writer.writerows(lines)
Of course, you need to adapt your change()
function:
当然,您需要调整您的change()
功能:
def change(lines):
a = input('ID')
for line in lines:
if line[0] == a:
d=str(input("phone"))
line[3]=d
break
else:
print "not"
回答by martineau
For a dictionary of strings such as the one you're dealing with, it could be done using only Python's built-in text processing capabilities.
对于诸如您正在处理的字符串字典,可以仅使用 Python 的内置文本处理功能来完成。
(Note this wouldn't work if the values are something else.)
(请注意,如果值是其他值,这将不起作用。)
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')
回答by Franck Dernoncourt
Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:
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"
FYI: NPY file viewer
仅供参考:NPY 文件查看器
回答by wordsforthewise
I haven't timed it but I bet h5 is faster than pickle; the filesize with compression is almost certainly smaller.
我没有计时,但我敢打赌 h5 比泡菜快;压缩后的文件大小几乎肯定会更小。
import deepdish as dd
dd.io.save(filename, {'dict1': dict1, 'dict2': dict2}, compression=('blosc', 9))
回答by junglejet
Save and load dict to file:
保存并加载 dict 到文件:
def save_dict_to_file(dic):
f = open('dict.txt','w')
f.write(str(dic))
f.close()
def load_dict_from_file():
f = open('dict.txt','r')
data=f.read()
f.close()
return eval(data)
回答by Patrick Stacey
Quick and dirty solution: convert the dict to string and save to file, e.g:
快速而肮脏的解决方案:将字典转换为字符串并保存到文件,例如:
#dict could be anything:
savedict = open('savedict001.txt', 'w')
savedict.write(str(dict))
savedict.close()
回答by simhumileco
We can also use the json
modulein the case when dictionaries or some other data can be easily mapped to JSONformat.
我们也可以json
在字典或其他一些数据可以轻松映射到JSON格式的情况下使用该模块。
import json
# Serialize data into file:
json.dump( data, open( "file_name.json", 'w' ) )
# Read data from file:
data = json.load( open( "file_name.json" ) )
This solution brings many benefits, eg works for Python 2.xand Python 3.xin an unchanged formand in addition, data saved in JSONformat can be easily transferred between many different platforms or programs. This data are also human-readable.
该解决方案带来了许多好处,例如以不变的形式适用于Python 2.x和Python 3.x,此外,以JSON格式保存的数据可以在许多不同的平台或程序之间轻松传输。这些数据也是人类可读的。
回答by Kavin Sabharwal
I would suggest saving your data using the JSON format instead of pickle format as JSON's files are human-readable which makes your debugging easier since your data is small. JSON files are also used by other programs to read and write data. You can read more about it here
我建议使用 JSON 格式而不是 pickle 格式保存您的数据,因为 JSON 的文件是人类可读的,这使您的调试更容易,因为您的数据很小。其他程序也使用 JSON 文件来读取和写入数据。你可以在这里阅读更多关于它的信息
You'll need to install the JSON module, you can do so with pip:
您需要安装 JSON 模块,您可以使用 pip 来安装:
pip install json
# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )
This creates a json file with the name myfile.
这将创建一个名为 myfile.json 的 json 文件。
# To read data from file:
data = json.load( open( "myfile.json" ) )
This reads and stores the myfile.json data in a data object.
这会读取 myfile.json 数据并将其存储在数据对象中。