如何在现代Python中向文件写入一行?我听说这是不赞成的:
print >>f, "hi there"
另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?
如何在现代Python中向文件写入一行?我听说这是不赞成的:
print >>f, "hi there"
另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?
当前回答
既然其他人已经回答了如何做到这一点,我将逐行回答它是如何发生的。
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,但我看到类更干净。
其他回答
我认为没有“正确”的方法。
我会用:
with open('myfile', 'a') as f:
f.write('hi there\n')
为了纪念蒂姆·托迪。
关于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以来,就一直如此简单。
使用os没有任何意义。linesep在非Windows系统上,它在Windows上产生错误的结果。
不要使用os.linesep!
当我需要大量编写新行时,我定义了一个使用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)
恕我直言,这是一种更实用、更简单的方法。
当你说行,它是指一些以“\n”字符结尾的序列化字符。行应该在最后一点,所以我们应该在每行的末尾考虑'\n'。下面是解决方案:
with open('YOURFILE.txt', 'a') as the_file:
the_file.write("Hello")
在追加模式下,每次写入后光标移动到新行,如果你想使用w模式,你应该在write()函数的末尾添加\n个字符:
the_file.write("Hello\n")
如果你想在列表中以每行格式插入项目,一种开始的方式可以是:
with open('somefile.txt', 'a') as the_file:
for item in items:
the_file.write(f"{item}\n")