[英]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.