将行写入文件的正确方法?

| 我习惯做
print >>f, \"hi there\"
但是,似乎ѭ1已经过时了。推荐使用哪种方法进行上述操作? 更新: 关于所有带有
\"\\n\"
的答案...这是通用的还是Unix专用的? IE,我应该在Windows上执行
\"\\r\\n\"
吗?     
已邀请:
        这应该很简单:
with open(\'somefile.txt\', \'a\') as the_file:
    the_file.write(\'Hello\\n\')
从文档:   写入以文本模式打开的文件时(默认),请勿将“ 5”用作行终止符;在所有平台上都使用一个\'\\ n \'代替。 一些有用的读物​​:
with
陈述
open()
\'a \'用于追加或使用 \'w \'截断书写
os
(尤其是
os.linesep
)     
        您应使用
print()
函数,该函数自Python 2.6+起可用
from __future__ import print_function  # Only needed for Python 2
print(\"hi there\", file=f)
对于Python 3,您不需要
import
,因为默认情况下是
print()
函数。 替代方法是使用:
f = open(\'myfile\', \'w\')
f.write(\'hi there\\n\')  # python will convert \\n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it
引用Python文档中有关换行符的内容:   在输出中,如果换行符为None,则写入的所有
\'\\n\'
字符都会转换为系统默认的行分隔符
os.linesep
。如果换行符是
\'\'
,则不会进行翻译。如果换行符是其他任何合法值,则将写入的所有“ 15”个字符转换为给定的字符串。     
        python文档建议采用以下方式:
with open(\'file_to_write\', \'w\') as f:
    f.write(\'file contents\')
所以这就是我通常的方式:) 来自docs.python.org的声明:   在处理文件时,最好使用\'with \'关键字   对象。这样做的好处是,文件在关闭后会正确关闭   即使在途中引发异常,其套件也会完成。它是   比编写等效的try-finally块还短得多。     
        关于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以来,事情就变得如此简单。 在非Windows系统上使用os.linesep是没有意义的,并且在Windows上会产生错误的结果。 请勿使用os.linesep!     
        我认为没有“正确”的方法。 我会用:
with open (\'myfile\', \'a\') as f: f.write (\'hi there\\n\')
纪念蒂姆·托迪(Tim Toady)。     
        在Python 3中,它是一个函数,但是在Python 2中,您可以将其添加到源文件的顶部:
from __future__ import print_function
那你做
print(\"hi there\", file=f)
    
        如果您要写入大量数据,而速度是一个问题,您可能应该选择with29ѭ。我进行了快速速度比较,在执行大量写入操作时,它的速度大大快于ѭ30considerably。
import time    

start = start = time.time()
with open(\"test.txt\", \'w\') as f:
    for i in range(10000000):
        # print(\'This is a speed test\', file=f)
        # f.write(\'This is a speed test\\n\')
end = time.time()
print(end - start)
平均
write
在我的机器上以2.45s完成,而
print
花费的时间大约是(9.76s)的4倍。话虽这么说,在大多数现实情况下这都不是问题。 如果您选择使用ѭ30go,则可能会发现您可能会不希望取消换行符,或将其替换为其他内容。这可以通过设置可选的
end
参数来完成,例如;
with open(\"test\", \'w\') as f:
    print(\'Foo1,\', file=f, end=\'\')
    print(\'Foo2,\', file=f, end=\'\')
    print(\'Foo3\', file=f)
无论您选择哪种方式,我建议使用
with
,因为它使代码更易于阅读。 更新:性能上的这种差异可以通过以下事实来解释:
write
被高度缓冲并在实际对磁盘进行任何写操作之前返回(请参见此答案),而
print
(可能)使用行缓冲。一个简单的测试就是检查长写的性能,因为行缓冲的缺点(在速度方面)不太明显。
start = start = time.time()
long_line = \'This is a speed test\' * 100
with open(\"test.txt\", \'w\') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + \'\\n\')
end = time.time()

print(end - start, \"s\")
现在,性能差异变得不那么明显了,
write
的平均时间为2.20s,
print
的平均时间为3.10s。如果您需要连接一串字符串才能获得这种良好的性能,那么
print
效率更高的用例就很少见了。     
        从3.5开始,您还可以为此使用pathlib:   Path.write_text(数据,编码=无,错误=无)      打开以文本模式指向的文件,向其中写入数据,然后关闭文件:
import pathlib

pathlib.Path(\'textfile.txt\').write_text(\'content\')
    
当您说Line时,它表示一些序列化的字符,它们以\'\\ n \'字符结尾。行应该在最后一点,所以我们应该在每行的末尾考虑\'\\ n \'。这是解决方案:
with open(\'YOURFILE.txt\', \'a\') as the_file:
    the_file.write(\'Hello\')
在追加模式下,每次写入光标后移至新行,如果要使用\'w \'模式,则应在write()函数末尾添加\'\\ n \'字符:
the_file.write(\'Hello\'+\'\\n\')
    
        也可以使用
io
模块,如下所示:
import io
my_string = \"hi there\"

with io.open(\"output_file.txt\", mode=\'w\', encoding=\'utf-8\') as f:
    f.write(my_string)
    
        您也可以尝试
filewriter
pip install filewriter
from filewriter import Writer

Writer(filename=\'my_file\', ext=\'txt\') << [\"row 1 hi there\", \"row 2\"]
写入
my_file.txt
接受具有
__str__
支持的可迭代对象或对象。     
        当我需要写很多新行时,我定义一个使用
print
函数的lambda:
out = open(file_name, \'w\')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl(\'Hi\')
这种方法的好处是可以利用
print
功能提供的所有功能。 更新:正如Georgy在评论部分中提到的那样,可以通过
partial
函数进一步改善此想法:
from functools import partial
fwl = partial(print, file=out)
恕我直言,这是一种功能更强,含糊不清的方法。     
        可以使用烧瓶中的文件写入文本:
filehandle = open(\"text.txt\", \"w\")
filebuffer = [\"hi\",\"welcome\",\"yes yes welcome\"]
filehandle.writelines(filebuffer)
filehandle.close()
    

要回复问题请先登录注册