2015-09-06 68 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')