2014-01-24 37 views
1

我有元素列表,並且我想使用python使用print()函數將以下元素寫入文件。無法使用python將元素列表寫入文件

Python的GUI:3.3版本

示例代碼:

D = {'b': 2, 'c': 3, 'a': 1} 
flog_out = open("Logfile.txt","w+") 
for key in sorted(D): 
    print(key , '=>', D[key],flog_out) 
flog_out.close() 

輸出,當我在IDLE GUI運行:

a => 1 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'> 
b => 2 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'> 
c => 3 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'> 

我沒有看到寫在輸出文件中的任何行。我嘗試使用flog_out.write(),它看起來我們可以在write()函數中傳遞一個參數。任何人都可以看看我的代碼,並告訴我是否錯過了一些東西。如果我寫它,我用

+0

能否請您期望的輸出添加到您的問題嗎? –

回答

0
D = {'b': 2, 'c': 3, 'a': 1} 
flog_out = open("Logfile.txt","w+") 
for key in sorted(D): 
    flog_out.write("{} => {}".format(key,D[key])) 
flog_out.close() 

雖然會上下文管理和dict.items()

D = {'b': 2, 'c': 3, 'a': 1} 
with open("Logfile.txt","w+") as flog_out: 
    for key,value in sorted(D.items()): 
     flog_out.write("{} => {}".format(key,value)) 
6

如果您指定一個類文件對象print,你需要使用一個named kwargfile=<descriptor>)句法。所有未命名的位置參數print將與空格連接在一起。

print(key , '=>', D[key], file=flog_out) 

作品。

2

Python Docs

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 

您的所有參數,key'=>'D[key],並flog_out,被包裝成*objects並打印到標準輸出。您需要添加關鍵字參數爲flog_out,像這樣:

print(key , '=>', D[key], file=flog_out) 

,以防止它處理它像剛剛另一個對象