正确的方式写入文件?

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

但是,似乎print >>已被弃用。 什么是build议的方式来做上面的线?

更新 :关于所有与"\n"答案…这是通用的还是Unix特有的? IE,我应该在Windows上做"\r\n"吗?

你应该使用Python 2.6+以后的print()函数

 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'字符都将转换为给定的string。

这应该像下面这样简单:

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

从文档:

编写以文本模式打开的文件时(默认),不要使用os.linesep作为行结束符; 而是在所有平台上使用单个“\ n”。

一些有用的阅读:

  • with声明
  • open()
    • 'a'是追加或使用
    • 'w'用截词写
  • os (特别是os.linesep

关于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!

python文档推荐这种方式:

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

所以这是我做的方式:)

来自docs.python.org的声明:

处理文件对象时,最好使用'with'关键字。 这有一个好处,就是文件在套件结束后可以正常closures,即使在路上出现exception。 它也比编写等价的try-finally块要短得多。

我不认为有一个“正确的”方法。

我会用:

 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) 

如果你正在写大量的数据和速度是一个问题,你应该使用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完成写作,而print花费了大约4倍(9.76s)。 这就是说,在大多数现实世界的情况下,这不会是一个问题。

如果您select使用print(..., file=f)您可能会发现需要不时地禁用换行符,或将其replace为其他内容。 这可以通过设置可选的end参数来完成,例如:

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

无论你select我会build议使用with因为它使代码更容易阅读。

更新 :这种性能差异是由write高度缓冲和事实之前返回写入磁盘实际发生的事实(看到这个答案 ),而print (可能)使用行缓冲的事实解释。 一个简单的testing就是检查长写入的性能,以及行caching方面的缺点(速度方面)不那么明显。

 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.20秒, print的平均时间为3.10秒。 如果你需要连接一串string来获得这个懒散的行,性能将会受到影响,所以print效率会更高的使用情况有点罕见。

当你说Line时,它表示一些以\ n结尾的string。 行应该在某一点上是最后的,所以我们应该在每行的末尾考虑'\ n'。 这里是解决scheme:

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

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

 the_file.write('Hello'+'\n')