例如:
with io.open('Example.txt','r',encoding='utf-8') as temp:
ExampleText=temp.readlines()[1]
Run Code Online (Sandbox Code Playgroud)
我是否需要手动关闭它,例如:
with io.open('Example.txt','r',encoding='utf-8') as temp:
ExampleText=temp.readlines()[1]
temp.close()
Run Code Online (Sandbox Code Playgroud)
TL;DR:不,当与with语句一起使用时,您不需要关闭流。
这样做的原因是TextIOWrapper返回的对象io.open是一个上下文管理器,它会close在退出上下文时调用底层文件。
为了验证这种行为,我们可以简单地__exit__显式调用,然后尝试读取文件:
>>> import io
>>> foo = io.open("foo.txt", "w+")
>>> foo.__exit__()
>>> foo.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
Run Code Online (Sandbox Code Playgroud)
这表明该文件实际上在__exit__被调用时已关闭,这在with块退出时自动发生。
请注意,有一个情况下文件描述符将不被关闭__exit__,这是其中文件描述符传递到的情况下io.open,而不是一个文件名或值一起对象False的closefd参数:
>>> import os
>>> file_ = open("foo.txt", "w+")
>>> foo = io.open(file_.fileno(), closefd=False)
>>> foo.__exit__()
>>> # the IOTextWrapper is closed
>>> foo.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
>>> # but the underlying file descriptor is not closed.
>>> os.read(file_.fileno(), 512)
b''
Run Code Online (Sandbox Code Playgroud)
如果True为closefd参数传递一个值,则传递的文件描述符在上下文退出时关闭:
>>> with io.open(file_.fileno(), closefd=True):
... pass
>>> os.read(file_.fileno(), 512)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor
Run Code Online (Sandbox Code Playgroud)
可以在此处找到详细描述此行为的文档。