如何在现代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")
其他回答
如果您希望避免使用write()或writelines()并自己用换行符连接字符串,则可以将所有行传递给print(),并将换行分隔符和文件句柄作为关键字参数。这个代码片段假设字符串没有结尾换行符。
print(line1, line2, sep="\n", file=f)
你不需要在结尾放一个特殊的换行符,因为print()为你做了。
如果列表中有任意数量的行,可以使用列表展开将它们全部传递给print()。
lines = ["The Quick Brown Fox", "Lorem Ipsum"]
print(*lines, sep="\n", file=f)
在Windows上使用“\n”作为分隔符是可以的,因为print()也会自动将其转换为Windows CRLF换行符(“\r\n”)。
我认为没有“正确”的方法。
我会用:
with open('myfile', 'a') as f:
f.write('hi there\n')
为了纪念蒂姆·托迪。
python文档推荐这样做:
with open('file_to_write', 'w') as f:
f.write('file contents\n')
所以这是我通常做的方式:)
docs.python.org声明:
在处理文件时使用'with'关键字是一个很好的实践 对象。这样做的好处是文件在关闭后被正确关闭 它的套件结束了,即使在此过程中引发了异常。它是 也比编写等价的try-finally块要短得多。
你也可以这样使用io模块:
import io
my_string = "hi there"
with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
f.write(my_string)
关于os.linesep:
下面是一个在Windows上精确的未经编辑的Python 2.7.1解释器会话:
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\r\n'
>>> f = open('myfile','w')
>>> f.write('hi there\n')
>>> f.write('hi there' + os.linesep) # same result as previous line ?????????
>>> f.close()
>>> open('myfile', 'rb').read()
'hi there\r\nhi there\r\r\n'
>>>
在Windows上:
不出所料,os。linesep不会产生与'\n'相同的结果。它不可能产生同样的结果。'hi there' + os。linesep等价于'hi there\r\n',它并不等价于'hi there\n'。
很简单:使用\n,它会自动转换为os.linesep。自从第一次将Python移植到Windows以来,就一直如此简单。
使用os没有任何意义。linesep在非Windows系统上,它在Windows上产生错误的结果。
不要使用os.linesep!