我习惯做print >>f, "hi there"
但是, print >>似乎已被弃用。建议的方法是什么?
更新 :关于所有那些带有"\n"答案...... 这是通用的还是特定于 Unix 的? IE,我应该在 Windows 上做"\r\n"吗?
您应该使用自 Python 2.6 + 以来可用的print()函数
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)对于 Python 3,您不需要import ,因为print()函数是默认值。
另一种方法是使用:
f = open('myfile', 'w')
f.write('hi there\n') # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call it引用有关换行符的Python 文档 :
在输出时,如果换行为 None,则写入的任何
'\n'字符都将转换为系统默认行分隔符os.linesep。如果换行是'',则不进行翻译。如果换行符是任何其他合法值,则写入的任何'\n'字符都将转换为给定的字符串。
这应该很简单:
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')来自文档:
在编写以文本模式打开的文件时,不要将
os.linesep用作行终止符(默认值); 在所有平台上使用单个 '\ n' 代替。
一些有用的阅读:
with声明 open() os (特别是os.linesep ) python 文档推荐这种方式:
with open('file_to_write', 'w') as f:
f.write('file contents')所以这就是我通常做的方式:)
来自docs.python.org 的声明:
在处理文件对象时,最好使用'with'关键字。这样做的好处是文件在套件完成后正确关闭,即使在途中引发了异常。它也比编写等效的 try-finally 块短得多。