简体   繁体   English

将字符串写入文件的pythonic方法是什么?

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

What's the difference between using File.write() and print>>File, ?使用File.write()print>>File,有什么区别?

Which is the pythonic way to write to file?写入文件的pythonic方式是什么?

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

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

Is there an advantage when using print>>File, ?使用print>>File,时有优势吗?

write() method writes to a buffer, which (the buffer) is flushed to a file whenever overflown/file closed/gets explicit request ( .flush() ). write()方法写入缓冲区,每当overflown / file关闭/获得显式请求( .flush() )时,(缓冲区)就会刷新到文件中。

print will block execution till actual writing to file completes. print将阻止执行,直到实际写入文件完成。

The first form is preferred because its execution is more efficient. 第一种形式是首选,因为它的执行效率更高。 Besides, the 2nd form is ugly and un-pythonic. 此外,第二种形式是丑陋和非pythonic。

The most pythonic way is the .write(). 最pythonic的方式是.write()。

I didn't even know the other way, but it doesn't even work with Python 3.3 我甚至不知道其他方式,但它甚至不适用于Python 3.3

A similar way of doing it would be: 类似的做法是:

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