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

Python 将行写入文件的正确方法?,python,file-io,Python,File Io,我习惯于做print>>f,“你好” 然而,print>>似乎越来越不受欢迎。建议用什么方法来完成上面这一行 更新: 关于所有这些答案,请使用“\n”…这是通用的还是特定于Unix的?例如,我应该在Windows上执行“\r\n”?我认为没有“正确”的方法 我将使用: with open ('myfile', 'a') as f: f.write ('hi there\n') 在memoriam.中,您应该使用自Python 2.6以来可用的print()函数+ from __future__

我习惯于做
print>>f,“你好”

然而,
print>>
似乎越来越不受欢迎。建议用什么方法来完成上面这一行

更新: 关于所有这些答案,请使用
“\n”
…这是通用的还是特定于Unix的?例如,我应该在Windows上执行
“\r\n”

我认为没有“正确”的方法

我将使用:

with open ('myfile', 'a') as f: f.write ('hi there\n')

在memoriam.

中,您应该使用自Python 2.6以来可用的
print()
函数+

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)
对于Python3,您不需要导入,因为
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
引用关于新行的内容:

在输出时,如果换行符为None,则写入的所有
'\n'
字符将转换为系统默认的行分隔符
os.linesep
。如果换行符为“
,则不会进行转换。如果换行符是任何其他合法值,则写入的任何
'\n'
字符都将转换为给定字符串


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

from __future__ import print_function
那你呢

print("hi there", file=f)

这应该简单到:

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

在写入以文本模式打开的文件时,不要使用
os.linesep
作为行终止符(默认设置);在所有平台上改用单个“\n”

一些有用的阅读:

    • “a”表示追加或使用
    • “w”以截断方式写入
  • (特别是)

关于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('file_to_write', 'w') as f:
    f.write('file contents\n')
所以我通常是这样做的:)

声明来自:

处理文件时,最好使用'with'关键字 物体。这样做的好处是,文件在关闭后会正确关闭 它的套件完成了,即使在途中出现了异常。它是 也比编写等效try finally块短得多


当您说行时,它表示一些以“\n”字符结尾的序列化字符。线应该在某个点上是最后的,所以我们应该在每行的末尾考虑'\n '。以下是解决方案:

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

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

the_file.write("Hello\n")
out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

如果您正在编写大量数据,并且速度是一个问题,那么您可能应该使用
f.write(…)
。我做了一个快速的速度比较,当执行大量写入时,它比打印(…,file=f)
要快得多

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.45秒完成,而
print
大约用了4倍的时间(9.76秒)。也就是说,在大多数真实场景中,这不会是一个问题

如果您选择使用
print(…,file=f)
,您可能会发现您可能希望不时地抑制换行符,或者用其他内容替换它。这可以通过设置可选的
end
参数来实现,例如:

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
无论您选择哪种方式,我都建议将
一起使用,因为它使代码更易于阅读

更新:这种性能差异的原因是
写入
是高度缓冲的,并且在写入磁盘之前返回(请参阅),而
打印
(可能)使用行缓冲。一个简单的测试就是检查长写操作的性能,在这种情况下,行缓冲的缺点(在速度方面)就不那么明显了

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")

性能差异现在变得不那么明显,写入
的平均时间为2.20秒,打印
的平均时间为3.10秒。如果您需要连接一组字符串以获得这种长行性能,那么
打印
效率更高的用例就有点少见了。

也可以使用
io
模块,如下所示:

import io
my_string = "hi there"

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

从3.5开始,您也可以为此目的使用:

Path.write_文本(数据,编码=None,错误=None)

以文本模式打开指向的文件,向其中写入数据,然后关闭该文件:


您也可以尝试
filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]
pip安装filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]
从文件编写器导入编写器

Writer(filename='my_file',ext='txt')当我需要写很多新行时,我定义一个lambda,它使用
打印
函数:

the_file.write("Hello\n")
out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')
这种方法的优点是可以利用
打印
功能提供的所有功能

更新:如评论部分所述,可以通过
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()

如果要避免使用
write()
writelines()
并将字符串与换行符连接起来,可以将所有行传递给
print()
,并将换行符和
exc_type: TypeError
exc_value: unsupported operand type(s) for +: 'int' and 'str
exc_traceback: <traceback object at 0x6af8ee10bc4d>
with open('somefile.txt', 'a') as the_file:
for item in python_list_of_strings:
    the_file.write(f"{item}\n")