gpt4 book ai didi

python - 在Python中将字典保存到文件(替代pickle)?

转载 作者:IT老高 更新时间:2023-10-28 20:32:26 26 4
gpt4 key购买 nike

已回答我最终还是选择了 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.

您能否给我另一种将字符串保存到文件的方法?

这是我希望它保存的格式

成员 = {'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")

最佳答案

当然,将其保存为 CSV:

import csv
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])

然后阅读它会是:

import csv
dict = {}
for key, val in csv.reader(open("input.csv")):
dict[key] = val

另一种选择是 json(json 用于 2.6+ 版本,或安装 simplejson 用于 2.5 及以下版本):

>>> import json
>>> dict = {"hello": "world"}
>>> json.dumps(dict)
'{"hello": "world"}'

关于python - 在Python中将字典保存到文件(替代pickle)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4893689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com