簡體   English   中英

無法使用python將元素列表寫入文件

[英]Unable to write list of elements to a file using python

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

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()函數中傳遞一個參數。 任何人都可以查看我的代碼並告訴我是否缺少某些內容。

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

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

作品。

Python文檔

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

您的所有參數key'=>'D[key]flog_out都打包到*objects並打印到stdout中。 您需要為flog_out添加關鍵字參數, flog_out所示:

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

為了防止它像另一個對象一樣對待

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM