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