如何在现代 Python 中将一行写入文件?我听说这已被弃用:
print >>f, "hi there"
另外,"\n"
是否适用于所有平台,或者我应该在 Windows 上使用 "\r\n"
吗?
最佳答案
这应该很简单:
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
来自文档:
Do not use
os.linesep
as a line terminator when writing files opened in text mode (the default); use a single'\n'
instead, on all platforms.
一些有用的阅读:
- The
with
statement -
open()
'a'
用于追加或使用'w'
用截断写法
-
os
(特别是os.linesep
)
关于python - 将行写入文件的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6159900/