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

print >>f, "hi there"

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


当前回答

在烧瓶文件中写入文本可以使用:

filehandle = open("text.txt", "w")
filebuffer = ["hi","welcome","yes yes welcome"]
filehandle.writelines(filebuffer)
filehandle.close()

其他回答

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

from __future__ import print_function

然后你做了

print("hi there", file=f)

在烧瓶文件中写入文本可以使用:

filehandle = open("text.txt", "w")
filebuffer = ["hi","welcome","yes yes welcome"]
filehandle.writelines(filebuffer)
filehandle.close()

你也可以这样使用io模块:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

这应该非常简单:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

来自文档:

不要使用os。当写入以文本模式打开的文件时(默认),Linesep作为行结束符;在所有平台上使用单个“\n”。

一些有用的阅读:

with语句 open () “a”是“追加”或“使用” 'w'表示截断 操作系统(特别是OS .linesep)

如果你想在列表中以每行格式插入项目,一种开始的方式可以是:

with open('somefile.txt', 'a') as the_file:
    for item in items:
        the_file.write(f"{item}\n")