如何在现代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()

其他回答

当我需要大量编写新行时,我定义了一个使用print函数的lambda:

out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

这种方法的好处是它可以利用打印函数的所有可用特性。

更新:正如Georgy在评论区提到的,可以通过partial函数进一步改进这个想法:

from functools import partial
fwl = partial(print, file=out)

恕我直言,这是一种更实用、更简单的方法。

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

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

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

the_file.write("Hello\n")

从3.5开始,你也可以使用pathlib来实现这个目的:

路径。write_text(data, encoding=None, errors=None) 以文本模式打开指向的文件,向其写入数据,然后关闭文件:

import pathlib

pathlib.Path('textfile.txt').write_text('content')

你也可以这样使用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:
    for item in items:
        the_file.write(f"{item}\n")