如何在现代Python中向文件写入一行?我听说这是不赞成的:

print >>f, "hi there"

另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?


当前回答

您应该使用print()函数,该函数自Python 2.6+以来可用

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

对于Python 3,您不需要导入,因为print()函数是默认的。

Python 3中的替代方法是使用:

with open('myfile', 'w') as f:
    f.write('hi there\n')  # python will convert \n to os.linesep

引用自Python文档中关于换行符的内容:

当写入输出到流时,如果newline为None,则写入的任何'\n'字符都将转换为系统默认的行分隔符os.linesep。如果换行符为''或'\n',则不进行转换。如果newline是任何其他合法值,则写入的任何'\n'字符都将转换为给定的字符串。

参见:读取和写入文件- Python教程

其他回答

在Python 3中,它是一个函数,但在Python 2中,你可以将它添加到源文件的顶部:

from __future__ import print_function

然后你做了

print("hi there", file=f)

python文档推荐这样做:

with open('file_to_write', 'w') as f:
    f.write('file contents\n')

所以这是我通常做的方式:)

docs.python.org声明:

在处理文件时使用'with'关键字是一个很好的实践 对象。这样做的好处是文件在关闭后被正确关闭 它的套件结束了,即使在此过程中引发了异常。它是 也比编写等价的try-finally块要短得多。

当你说行,它是指一些以“\n”字符结尾的序列化字符。行应该在最后一点,所以我们应该在每行的末尾考虑'\n'。下面是解决方案:

with open('YOURFILE.txt', 'a') as the_file:
    the_file.write("Hello")

在追加模式下,每次写入后光标移动到新行,如果你想使用w模式,你应该在write()函数的末尾添加\n个字符:

the_file.write("Hello\n")

您应该使用print()函数,该函数自Python 2.6+以来可用

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

对于Python 3,您不需要导入,因为print()函数是默认的。

Python 3中的替代方法是使用:

with open('myfile', 'w') as f:
    f.write('hi there\n')  # python will convert \n to os.linesep

引用自Python文档中关于换行符的内容:

当写入输出到流时,如果newline为None,则写入的任何'\n'字符都将转换为系统默认的行分隔符os.linesep。如果换行符为''或'\n',则不进行转换。如果newline是任何其他合法值,则写入的任何'\n'字符都将转换为给定的字符串。

参见:读取和写入文件- Python教程

我认为没有“正确”的方法。

我会用:

with open('myfile', 'a') as f:
    f.write('hi there\n')

为了纪念蒂姆·托迪。