问题
def __init__(self):
self.bok = {'peter': 123, 'maria': 321, 'harry': 888}
def save(self):
file = open('test.txt', 'w')
file.write(str(self.bok))
file.close()
print "File was successfully saved."
def load(self):
try:
file = open('test.txt', 'r')
newdict = eval(file.read())
self.bok = newdict
file.close()
print "File was successfully loaded."
except IOError:
print "No file was found."
return
How do i make it look like this inside the text file:
value1:key1
value2:key2
==>
123:peter
321:maria
Currently it looks like normal, a dictionary:
{'peter': 123, 'maria': 321, 'harry': 888}
But the issue that would appear is to load the file since it doesn't look like a dictionary anymore?
(Load = loads the dictionary from a .txt file to self.bok{})
(Save = saves the dictionary to a .txt file)
回答1:
import csv
def save(self, filepath):
with open(filepath, 'w') as fout:
outfile = csv.writer(fout, delimiter=":")
for k,v in self.bok.iteritems():
outfile.writerow([v,k])
def load(self, filepath):
if not os.path.isfile(filepath):
print "No file was found"
return
with open(filepath) as infile:
for v,k in csv.reader(infile, delimiter=":"):
self.bok[k] = v
Without any help from csv:
def save(self, filepath):
with open(filepath, 'w') as outfile:
for k,v in self.bok.iteritems():
outfile.write("{}:{}\n".format(v,k))
def load(self, filepath):
if not os.path.isfile(filepath):
print "No file was found"
return
with open(filepath) as infile:
for line in infile:
v,k = line.strip().split(":")
self.bok[k] = v
来源:https://stackoverflow.com/questions/33160122/python-2-7-8-dictionary-to-file-and-back-with-style