簡體   English   中英

將字符串寫入文件的pythonic方法是什么?

[英]What is the pythonic way to write strings to file?

使用File.write()print>>File,有什么區別?

寫入文件的pythonic方式是什么?

>>> with open('out.txt','w') as fout:
...     fout.write('foo bar')
... 

>>> with open('out.txt', 'w') as fout:
...     print>>fout, 'foo bar'
... 

使用print>>File,時有優勢嗎?

write()方法寫入緩沖區,每當overflown / file關閉/獲得顯式請求( .flush() )時,(緩沖區)就會刷新到文件中。

print將阻止執行,直到實際寫入文件完成。

第一種形式是首選,因為它的執行效率更高。 此外,第二種形式是丑陋和非pythonic。

最pythonic的方式是.write()。

我甚至不知道其他方式,但它甚至不適用於Python 3.3

類似的做法是:

fout = open("out.txt", "w")
fout.write("foo bar")
#fout.close() if you were done with the writing

暫無
暫無

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

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