2015-09-06 71 views
-1

我在python中遇到了问题。我想创建一个函数来从用户打印一个文件到一个新文件(example.txt)。打印为python中的字典

旧的文件是这样的:

{'a':1,'b':2...) 

,我想喜欢新的文件:

a 1,b 2(the next line) 

但是我做可以运行的功能,但它并不显示在任何新文件。有人能帮助我吗。

def printing(file): 
    infile=open(file,'r') 
    outfile=open('example.txt','w') 

    dict={} 
    file=dict.values() 
    for key,values in file: 
     print key 
     print values 
    outfile.write(str(dict)) 
    infile.close() 
    outfile.close() 
+1

也使用像'dict'这样的名称不推荐 –

+0

您使用的命名约定有点不整齐。 – ABcDexter

+0

你的意思是'dict'? –

回答

1

这将创建一个新的空字典:

dict={} 

dict不是一个变量一个好名字,因为它阴影内置dict类型,可能会造成混乱。

这使得名file点在字典中的值:

file=dict.values() 

file将是空的,因为dict是空的。

这对file中的值对进行迭代。

for key,values in file: 

由于file是空的,所以不会发生任何事情。但是,如果file不为空,则其中的值必须为值对,才能将它们拆分为key,values

这种转换dict为字符串,并将其写入到outfile

outfile.write(str(dict)) 

调用writenon-str对象将安韦调用str就可以了,所以你可以只说:

outfile.write(dict) 

您实际上没有对infile做任何事情。

0

你可以使用re模块(正则表达式)来实现你所需要的。解决方案可能就是这样。当然,您可以定制以适应您的需求。希望这可以帮助。

import re 
def printing(file): 
    outfile=open('example.txt','a') 
    with open(file,'r') as f: 
     for line in f: 
      new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', line) 
      outfile.write(new_string) 

printing('output.txt')