在 Python 中将字典保存到文件(替代 pickle)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4893689/
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
Save a dictionary to a file (alternative to pickle) in Python?
提问by wKavey
AnsweredI ended up going with pickle at the end anyway
回答我最后还是吃了泡菜
Ok so with some advice on another question I asked I was told to use pickle to save a dictionary to a file.
好的,我就另一个问题提出了一些建议,我被告知使用 pickle 将字典保存到文件中。
The dictionary that I was trying to save to the file was
我试图保存到文件中的字典是
members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
When pickle saved it to the file... this was the format
当pickle将它保存到文件时......这是格式
(dp0
S'Test'
p1
S'Test1'
p2
sS'Test2'
p3
S'Test2'
p4
sS'Starspy'
p5
S'SHSN4N'
p6
s.
Can you please give me an alternative way to save the string to the file?
你能给我一种将字符串保存到文件的替代方法吗?
This is the format that I would like it to save in
这是我希望它保存的格式
members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
成员 = {'Starspy':'SHSN4N','测试':'Test1'}
Complete Code:
完整代码:
import sys
import shutil
import os
import pickle
tmp = os.path.isfile("members-tmp.pkl")
if tmp == True:
os.remove("members-tmp.pkl")
shutil.copyfile("members.pkl", "members-tmp.pkl")
pkl_file = open('members-tmp.pkl', 'rb')
members = pickle.load(pkl_file)
pkl_file.close()
def show_menu():
os.system("clear")
print "\n","*" * 12, "MENU", "*" * 12
print "1. List members"
print "2. Add member"
print "3. Delete member"
print "99. Save"
print "0. Abort"
print "*" * 28, "\n"
return input("Please make a selection: ")
def show_members(members):
os.system("clear")
print "\nNames", " ", "Code"
for keys in members.keys():
print keys, " - ", members[keys]
def add_member(members):
os.system("clear")
name = raw_input("Please enter name: ")
code = raw_input("Please enter code: ")
members[name] = code
output = open('members-tmp.pkl', 'wb')
pickle.dump(members, output)
output.close()
return members
#with open("foo.txt", "a") as f:
# f.write("new line\n")
running = 1
while running:
selection = show_menu()
if selection == 1:
show_members(members)
print "\n> " ,raw_input("Press enter to continue")
elif selection == 2:
members == add_member(members)
print members
print "\n> " ,raw_input("Press enter to continue")
elif selection == 99:
os.system("clear")
shutil.copyfile("members-tmp.pkl", "members.pkl")
print "Save Completed"
print "\n> " ,raw_input("Press enter to continue")
elif selection == 0:
os.remove("members-tmp.pkl")
sys.exit("Program Aborted")
else:
os.system("clear")
print "That is not a valid option!"
print "\n> " ,raw_input("Press enter to continue")
采纳答案by David Wolever
Sure, save it as CSV:
当然,将其另存为 CSV:
import csv
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])
Then reading it would be:
然后阅读它将是:
import csv
dict = {}
for key, val in csv.reader(open("input.csv")):
dict[key] = val
Another alternative would be json (jsonfor version 2.6+, or install simplejsonfor 2.5 and below):
另一种选择是 json (json对于 2.6+ 版本,或安装simplejson2.5 及以下版本):
>>> import json
>>> dict = {"hello": "world"}
>>> json.dumps(dict)
'{"hello": "world"}'
回答by Pedro Matiello
The YAML format (via pyyaml) might be a good option for you:
YAML 格式(通过 pyyaml)可能是一个不错的选择:
http://en.wikipedia.org/wiki/Yaml
http://en.wikipedia.org/wiki/Yaml
回答by Glenn Maynard
The most common serialization format for this nowadays is JSON, which is universally supported and represents simple data structures like dictionaries very clearly.
现在最常见的序列化格式是 JSON,它得到普遍支持,并且非常清楚地表示简单的数据结构,如字典。
>>> members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
>>> json.dumps(members)
'{"Test": "Test1", "Starspy": "SHSN4N"}'
>>> json.loads(json.dumps(members))
{u'Test': u'Test1', u'Starspy': u'SHSN4N'}
回答by Mike McKerns
While I'd suggest pickle, if you want an alternative, you can use klepto.
虽然我建议pickle,但如果你想要一个替代品,你可以使用klepto.
>>> init = {'y': 2, 'x': 1, 'z': 3}
>>> import klepto
>>> cache = klepto.archives.file_archive('memo', init, serialized=False)
>>> cache
{'y': 2, 'x': 1, 'z': 3}
>>>
>>> # dump dictionary to the file 'memo.py'
>>> cache.dump()
>>>
>>> # import from 'memo.py'
>>> from memo import memo
>>> print memo
{'y': 2, 'x': 1, 'z': 3}
With klepto, if you had used serialized=True, the dictionary would have been written to memo.pklas a pickled dictionary instead of with clear text.
使用klepto,如果您使用了serialized=True,则字典将被写入memo.pkl为腌制字典而不是明文。
You can get kleptohere: https://github.com/uqfoundation/klepto
你可以到klepto这里:https: //github.com/uqfoundation/klepto
dillis probably a better choice for pickling then pickleitself, as dillcan serialize almost anything in python. kleptoalso can use dill.
dill可能是酸洗的更好选择pickle,因为它dill可以序列化 python 中的几乎任何东西。 klepto也可以使用dill。
You can get dillhere: https://github.com/uqfoundation/dill
你可以到dill这里:https: //github.com/uqfoundation/dill
回答by gseattle
Although, unlike pp.pprint(the_dict), this won't be as pretty, will be run together, str()at least makes a dictionary savable in a simple way for quick tasks:
虽然与 不同pp.pprint(the_dict),这不会那么漂亮,会一起运行,str()但至少可以以简单的方式保存字典以执行快速任务:
f.write( str( the_dict ) )
回答by serv-inc
You asked
你问
Ill give it a shot. How do I specify what file to dump it to/load it from?
我会试一试。如何指定将其转储到/从中加载的文件?
Apart from writing to a string, the jsonmodule provides a dump()-method, which writes to a file:
除了写入字符串外,该json模块还提供了一个dump()写入文件的-method:
>>> a = {'hello': 'world'}
>>> import json
>>> json.dump(a, file('filename.txt', 'w'))
>>> b = json.load(file('filename.txt'))
>>> b
{u'hello': u'world'}
There is a load()method for reading, too.
load()读书也是有方法的。

