我知道在 Python 中 file.close()
方法没有任何返回值,但我找不到任何关于它在某些情况下是否抛出异常的信息。如果它也没有这样做,那么我想这个问题的第二部分是多余的。
如果是这样,那么处理 file.close()
方法在用于打开文件的“with”语句中抛出异常的“正确”方法是什么?
在打开并成功读取文件后,file.close()
是否会立即失败?
最佳答案
是的,file.close()
可以抛出一个IOError
异常。例如,当文件系统使用配额时,就会发生这种情况。查看C close()
function man page :
Not checking the return value of
close()
is a common but nevertheless serious programming error. It is quite possible that errors on a previouswrite(2)
operation are first reported at the finalclose()
. Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.
C close()
函数的非零返回值导致 Python 引发 IOError
异常。
如果你想处理这个异常,在 with
语句的 周围放置一个 try...except
block :
try:
with open(filename, mode) as fileobj:
# do something with the open file object
except IOError as exc:
# handle the exception
当然,IOError
也可能在打开 期间抛出。
关于python - Python 中 with 语句中的 file.close() 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766524/