con risposta ho finito per andare con salamoia alla fine comunqueSalva un dizionario in un file (alternativa al pickle) in Python?
Ok, quindi con qualche consiglio su un'altra domanda ho chiesto mi è stato detto di usare salamoia per salvare un dizionario in un file.
Il dizionario che stavo cercando di salvare il file è stato
members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
Quando salamoia è salvato nel file ... questo è stato il formato
(dp0
S'Test'
p1
S'Test1'
p2
sS'Test2'
p3
S'Test2'
p4
sS'Starspy'
p5
S'SHSN4N'
p6
s.
Potete per favore mi dia un modo alternativo per salvare la stringa nel file?
Questo è il formato che vorrei per salvare in
membri = { 'Starspy': 'SHSN4N', 'Test': 'Test1'}
codice completo:
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")
Cosa c'è che non va nel formato? Come vorresti che fosse? –
Mi piacerebbe che salvi come un dizionario normale E.g. membri = {'Starspy': 'SHSN4N', 'Test': 'Test1'} – wKavey
Vedere [Memorizzazione dei dizionari Python] (http://stackoverflow.com/q/7100125/562769) –