如何在现代Python中向文件写入一行?我听说这是不赞成的:
print >>f, "hi there"
另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?
如何在现代Python中向文件写入一行?我听说这是不赞成的:
print >>f, "hi there"
另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?
当前回答
如果你想在列表中以每行格式插入项目,一种开始的方式可以是:
with open('somefile.txt', 'a') as the_file:
for item in items:
the_file.write(f"{item}\n")
其他回答
python文档推荐这样做:
with open('file_to_write', 'w') as f:
f.write('file contents\n')
所以这是我通常做的方式:)
docs.python.org声明:
在处理文件时使用'with'关键字是一个很好的实践 对象。这样做的好处是文件在关闭后被正确关闭 它的套件结束了,即使在此过程中引发了异常。它是 也比编写等价的try-finally块要短得多。
当我需要大量编写新行时,我定义了一个使用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)
恕我直言,这是一种更实用、更简单的方法。
如果你想在列表中以每行格式插入项目,一种开始的方式可以是:
with open('somefile.txt', 'a') as the_file:
for item in items:
the_file.write(f"{item}\n")
我认为没有“正确”的方法。
我会用:
with open('myfile', 'a') as f:
f.write('hi there\n')
为了纪念蒂姆·托迪。
在烧瓶文件中写入文本可以使用:
filehandle = open("text.txt", "w")
filebuffer = ["hi","welcome","yes yes welcome"]
filehandle.writelines(filebuffer)
filehandle.close()