如何在现代Python中向文件写入一行?我听说这是不赞成的:

print >>f, "hi there"

另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?


当前回答

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

我会用:

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

为了纪念蒂姆·托迪。

其他回答

你也可以试试文件编辑器

PIP安装文件写入器

from filewriter import Writer

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

写入my_file.txt

接受一个可迭代对象或具有__str__支持的对象。

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

我会用:

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

为了纪念蒂姆·托迪。

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

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

对于Python 3,您不需要导入,因为print()函数是默认的。

Python 3中的替代方法是使用:

with open('myfile', 'w') as f:
    f.write('hi there\n')  # python will convert \n to os.linesep

引用自Python文档中关于换行符的内容:

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

参见:读取和写入文件- Python教程

既然其他人已经回答了如何做到这一点,我将逐行回答它是如何发生的。

with FileOpenerCM('file.txt') as fp: # is equal to "with open('file.txt') as fp:"
      fp.write('dummy text')

这就是所谓的context manager, with block中的任何东西都是context manager。让我们看看这是如何发生的。

class FileOpenerCM:
     def __init__(self, file, mode='w'):
         self.file = open(file, mode)
      
     def __enter__(self):
          return self.file
      
     def __exit__(self, exc_type, exc_value, exc_traceback):
         self.file.close()

第一个方法__init__是(如你所知)对象的初始化方法。每当创建一个对象时,obj。__init__被明确调用。这是你放init代码的地方。

第二个方法__enter__有点有趣。有些人可能没见过它,因为它是上下文管理器的特定方法。它返回的是在as关键字之后分配给变量的值。在这里,是fp。

最后一个方法是在捕获错误后或代码退出with块时运行的方法。Exc_type, exc_value, exc_traceback变量是保存block内部发生错误的值的变量。例如,

exc_type: TypeError
exc_value: unsupported operand type(s) for +: 'int' and 'str
exc_traceback: <traceback object at 0x6af8ee10bc4d>

从前两个变量中,您可以获得关于错误的足够信息。老实说,我不知道第三个变量有什么用,但对我来说,前两个就足够了。如果您想对上下文管理器做更多的研究,当然可以这样做,并注意编写类并不是编写上下文管理器的唯一方法。使用contextlib,您还可以通过函数(实际上是生成器)编写上下文管理器。看不看完全取决于你。你当然可以试试 生成器函数与contextlib,但我看到类更干净。

当我需要大量编写新行时,我定义了一个使用print函数的lambda:

out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

这种方法的好处是它可以利用打印函数的所有可用特性。

更新:正如Georgy在评论区提到的,可以通过partial函数进一步改进这个想法:

from functools import partial
fwl = partial(print, file=out)

恕我直言,这是一种更实用、更简单的方法。