在Python中将字典保存到文件(替代pickle)?
已回答 无论如何,我最后还是选择了pickle
好吧,根据我问的另一个问题的一些建议,我被告知使用pickle 将字典保存到文件中。
我试图保存到文件的字典是
members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
当 pickle 将其保存到文件时...这是格式
(dp0
S'Test'
p1
S'Test1'
p2
sS'Test2'
p3
S'Test2'
p4
sS'Starspy'
p5
S'SHSN4N'
p6
s.
您能给我另一种将字符串保存到文件的方法吗?
这是我希望它保存在
Members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
中的格式完整代码:
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")
Answered I 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.
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
(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'}
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当然,将其保存为 CSV:
然后读取它:
另一种选择是 json(对于 2.6+ 版本,安装
json
,对于 2.5 及以下版本,安装simplejson
):Sure, save it as CSV:
Then reading it would be:
Another alternative would be json (
json
for version 2.6+, or installsimplejson
for 2.5 and below):目前最常见的序列化格式是 JSON,它受到普遍支持,并且非常清楚地表示简单的数据结构(例如字典)。
The most common serialization format for this nowadays is JSON, which is universally supported and represents simple data structures like dictionaries very clearly.
YAML 格式(通过 pyyaml)可能是您的一个不错的选择:
http://en.wikipedia.org/维基/Yaml
http://pypi.python.org/pypi/PyYAML
The YAML format (via pyyaml) might be a good option for you:
http://en.wikipedia.org/wiki/Yaml
http://pypi.python.org/pypi/PyYAML
尽管与 pp.pprint(the_dict) 不同,这不会那么漂亮,会一起运行,但 str() 至少可以以简单的方式保存字典对于快速任务:
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:您问了
除了写入字符串之外,
json
模块还提供 < code>dump() 方法,写入文件:还有一个
load()
方法用于读取。You asked
Apart from writing to a string, the
json
module provides adump()
-method, which writes to a file:There is a
load()
method for reading, too.虽然我建议使用
pickle
,但如果您想要替代方案,则可以使用klepto
。对于
klepto
,如果您使用了serialized=True
,字典将被写入memo.pkl
作为 pickled 字典,而不是使用clear文本。您可以在此处获取
klepto
:https://github.com/uqfoundation/kleptodill
可能是比pickle
本身更好的 pickle 选择,因为dill
几乎可以序列化 python 中的任何内容。klepto
也可以使用dill
。您可以在此处获取
dill
:https://github.com/uqfoundation/dillWhile I'd suggest
pickle
, if you want an alternative, you can useklepto
.With
klepto
, if you had usedserialized=True
, the dictionary would have been written tomemo.pkl
as a pickled dictionary instead of with clear text.You can get
klepto
here: https://github.com/uqfoundation/kleptodill
is probably a better choice for pickling thenpickle
itself, asdill
can serialize almost anything in python.klepto
also can usedill
.You can get
dill
here: https://github.com/uqfoundation/dill