使用 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()
方法写入缓冲区,每当溢出/文件关闭/收到显式请求时,缓冲区(缓冲区)就会刷新到文件中(.flush()
).
print
将阻止执行,直到实际写入文件完成。
首选第一种形式,因为它的执行效率更高。此外,第二种形式是丑陋的和非 pythonic 的。
关于python - 将字符串写入文件的 pythonic 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868484/