我习惯于做 "print >>f,"hi there""。
然而,似乎print >>
正在被废弃。建议用什么方法来做上面这一行?
更新。
关于所有那些带有"&n"
的答案...这是通用的还是Unix特有的?IE,我应该在Windows上做"\r\n"
吗?
这应该是简单的。
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
从文档中。
当以文本模式打开文件时,不要使用
os.linesep
作为行结束符(默认)。 在所有平台上使用一个'/n' 而不是在所有平台上使用。
一些有用的阅读。
with
语句open()
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
。如果换行符是"''",则不发生翻译。如果换行符是其他合法值中的任何一个,写下的任何'\n'
字符都被翻译成给定的字符串。
python文档][1]中推荐了这种方式。
with open('file_to_write', 'w') as f:
f.write('file contents')
所以我通常是这样做的 :)
语句来自[docs.python.org][1]。
当处理文件时,使用'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'
等同于
'hi there\rn\',它**不**等同于
'hi there&#n\39;`。就是这么简单。
使用 n
会被自动翻译成 os.lineep.,而且从 Python 第一次移植到 Windows 时起就一直这么简单。
在非 Windows 系统上使用 os.linesep 是没有意义的,它在 Windows 上会产生错误的结果。
不要使用 os.lineep!。
如果你要写很多数据,而且速度是个问题,你可能应该选择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
从3.5开始,你也可以使用[pathlib][1]来实现这个目的。 >.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
当你说Line的时候,它的意思是一些序列化的字符,这些字符是以'\n'。 字符。 Line应该在某个点上是最后一个,所以我们应该考虑在每一行的末尾加上'\n'。 在每一行的最后。 下面是解决方案。
with open('YOURFILE.txt', 'a') as the_file:
the_file.write('Hello')
在append模式下,每次写完后光标都会移动到新的行,如果你想使用'w' 模式,你应该在write()函数末尾添加'/n'。 字符在write()函数的最后。
the_file.write('Hello'+'\n')