向文件写行的正确方法是什么?

我习惯于做 "print >>f,"hi there""。

然而,似乎print >>正在被废弃。建议用什么方法来做上面这一行?

更新。 关于所有那些带有"&n"的答案...这是通用的还是Unix特有的?IE,我应该在Windows上做"\r\n"吗?

对该问题的评论 (3)
解决办法

这应该是简单的。

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

从文档中。

当以文本模式打开文件时,不要使用os.linesep作为行结束符(默认)。 在所有平台上使用一个'/n' 而不是在所有平台上使用。

一些有用的阅读。

评论(10)

你应该使用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。如果换行符是"''",则不发生翻译。如果换行符是其他合法值中的任何一个,写下的任何'\n'字符都被翻译成给定的字符串。

评论(18)

python文档][1]中推荐了这种方式。

with open('file_to_write', 'w') as f:
    f.write('file contents')

所以我通常是这样做的 :)

语句来自[docs.python.org][1]。

当处理文件时,使用'with'关键字是一个很好的做法。

对象。 这样做的好处是,文件在完成了

其套房装修,即使在途中提出异常。 它是

也比写等价的try-finally块短得多。

[1]: http://docs.python.org/tutorial/inputoutput.html

评论(3)

关于 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\rn\',它**不**等同于'hi there&#n\39;`。

就是这么简单。 使用 n 会被自动翻译成 os.lineep.,而且从 Python 第一次移植到 Windows 时起就一直这么简单。

在非 Windows 系统上使用 os.linesep 是没有意义的,它在 Windows 上会产生错误的结果。

不要使用 os.lineep!

评论(7)

我不认为有一种"正确"的方式。

我将使用。

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

纪念Tim Toady

评论(7)

在Python 3中,它是一个函数,但在Python 2中,你可以把它加到源文件的顶部。

from __future__ import print_function

然后你做

print("hi there", file=f)
评论(0)

如果你要写很多数据,而且速度是个问题,你可能应该选择f.write(...)。 我做了一个快速的速度比较,当执行大量写入时,它比print(..., 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)

在我的机器上,```写`平均2.45s就完成了,而打印````则花了大约4倍的时间(9.76s)。 也就是说,在大多数实际场景中,这不会是一个问题。

如果你选择使用print(..., file=f),你可能会发现,你会时不时地想要抑制换行,或者用其他东西来代替它。 这可以通过设置可选的"end"参数来实现,例如。

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)

更新。 这种性能上的差异可以解释为write是高度缓冲的,并且在任何写入磁盘的行为实际发生之前就返回(见[本回答][1]),而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会更有效率的用例有点少。

[1]: https://stackoverflow.com/questions/3857052/why-is-printing-to-stdout-so-slow-can-it-be-sped-up

评论(0)

从3.5开始,你也可以使用[pathlib][1]来实现这个目的。 &gt.path.write_text(data, encoding=None, errors=None) Path.write_text(data, encoding=None, errors=None)

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

import pathlib

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

[1]: https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_text

评论(0)

当你说Line的时候,它的意思是一些序列化的字符,这些字符是以'\n&#39。 字符。 Line应该在某个点上是最后一个,所以我们应该考虑在每一行的末尾加上'\n&#39。 在每一行的最后。 下面是解决方案。

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

在append模式下,每次写完后光标都会移动到新的行,如果你想使用'w' 模式,你应该在write()函数末尾添加'/n'。 字符在write()函数的最后。

the_file.write('Hello'+'\n')
评论(1)

也可以使用io模块,如。

import io
my_string = "hi there"

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

你也可以试试filewriter

pip install filewriter

从filewriter导入Writer

Writer(filename=&#39;my_file&#39;, ext=&#39;txt&#39;) <&lt。

写入my_file.txt

取一个支持"str"的可迭代对象或对象。

评论(0)

当我需要经常写新行时,我定义了一个lambda,使用print函数。

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)

IMHO,这是一种更实用、更不神秘的方法。

1:

评论(3)