Python 2.7.8 - Dictionary to file and back with style

本小妞迷上赌 提交于 2019-12-12 02:21:02

问题


 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!