[英]Does “with io.open” close the file automatically?
For example: 例如:
with io.open('Example.txt','r',encoding='utf-8') as temp:
ExampleText=temp.readlines()[1]
Do I need to close it manually, like: 我需要手动关闭它,例如:
with io.open('Example.txt','r',encoding='utf-8') as temp:
ExampleText=temp.readlines()[1]
temp.close()
TL;DR: No, you don't need to close the stream when used with the with
statement. TL; DR:不,与with
语句with
使用时,不需要关闭流。
The reason for this is that the TextIOWrapper
object returned by io.open
is a context manager which will call close
on the underlying file when a context is exited. 原因是io.open
返回的TextIOWrapper
对象是一个上下文管理器,它将在退出上下文时调用基础文件上的close
。
To verify this behavior we can simply call __exit__
explicitly and then try to read the file: 要验证此行为,我们只需显式调用__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.
Which demonstrates that the file is in fact closed when __exit__
is called, which happens automatically when the with
block is exited. 这表明在调用__exit__
时文件实际上是关闭的,这在退出with
块时会自动发生。
Note that there is one case where the file descriptor will not be closed on __exit__
and that is the case where a file-descriptor is passed to io.open
rather than a file name or object along with a value of False
for the closefd
argument: 请注意,有一种情况是文件描述符不会在__exit__
上关闭, __exit__
将文件描述符传递给io.open
而不是文件名或对象以及closefd
参数的值为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''
If you pass a value of True
for the closefd
argument than the passed file descriptor is closed on context exit: 如果为closefd
参数传递的值为True
,则在上下文退出时关闭传递的文件描述符:
>>> 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
Docs describing this behavior in detail can be found here . 可以在此处找到详细描述此行为的文档。
不,您不需要手动关闭它。
If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False. 如果给出了文件描述符,则在关闭返回的I / O对象时将关闭该文件描述符,除非将closefd设置为False。
So if you provide a file descriptor and want to manually close it (because you might use descriptor later) you call it as 因此,如果您提供文件描述符并希望手动关闭它(因为您可能稍后使用描述符),则将其称为
import os
import io
fd = os.open("foo.txt", os.O_RDONLY)
io.open(fd, 'r', encoding='utf-8', closefd=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.