Python 2.7.8 - 字典到文件并带有样式 [英] Python 2.7.8 - Dictionary to file and back with style

查看:203
本文介绍了Python 2.7.8 - 字典到文件并带有样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ _ code> 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 )
打印文件已成功保存。

def load(self):
try:
file = open('test.txt','r')
newdict = eval(file.read ))
self.bok = newdict
file.close()
print文件已成功加载。
除了IOError:
打印找不到文件。
return

我如何在文本文件中看起来像这样:

value1:key1

value2:key2

==>

123:peter

321:maria

目前看起来像正常字典:

{'peter':123,'maria':321,'harry':888}

但问题是会出现是加载文件,因为它看起来不像字典了吗?



(Load =将字典从.txt文件加载到self.bok {})

(保存=将字典保存到.txt文件)

解决方案

  import csv 

def save ,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):
如果不是os.path.isfile(filepath):
打印没有找到文件
返回
打开(文件路径)为infile:
为v,k在csv.reader(infile,delimiter =:):
self.bok [k] = v

没有来自 csv :

  def save(self,filepath):
with open(filepath ,'w')作为outfile:
for k,v in self.bok.iteritems():
outfile.write({}:{} \\\
.format(v,k) )

def l oad(self,filepath):
如果不是os.path.isfile(filepath):
print没有找到文件
返回
与open(filepath)作为infile:
for infile:
v,k = line.strip()。split(:)
self.bok [k] = v


 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)

解决方案

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

这篇关于Python 2.7.8 - 字典到文件并带有样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆