file.close() Python 中 with 语句中的异常处理
file.close() exception handling inside a with statement in Python
我知道在 Python 中 file.close()
方法没有任何 return 值,但我找不到任何关于它在某些情况下是否抛出异常的信息.如果它也不这样做,那么我想这个问题的第二部分是多余的。
如果是,那么 "correct" 处理 file.close()
方法在用于打开文件的 "with" 语句中抛出异常的方法是什么?
是否存在文件打开并成功读取后file.close()
会立即失败的情况?
您可以使用
file object = open(file_name [, access_mode][, buffering])
然后你检查
file.closed
如果文件已关闭,则为 return 真,否则为假。
close
可以抛出异常,例如,如果您 运行 磁盘 space 试图刷新您的最后一次写入,或者如果您拔出 USB 记忆棒文件已打开。
至于如何正确处理这个问题,这取决于您的应用程序的细节。也许您想向用户显示一条错误消息。也许你想关闭你的程序。也许您想重试您正在做的任何事情,但使用不同的文件。无论您选择哪种响应,它都可能会在您的程序最适合处理它的任何层中使用 try
-except
块来实现。
是的,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 previous write(2)
operation are first reported at the final close()
. 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()
函数的非零 return 值导致 Python 引发 IOError
异常。
如果您想处理这个异常,请在 with
语句 周围放置一个 try...except
块 :
try:
with open(filename, mode) as fileobj:
# do something with the open file object
except IOError as exc:
# handle the exception
当然,IOError
也可能是在 开启 时抛出的。
我知道在 Python 中 file.close()
方法没有任何 return 值,但我找不到任何关于它在某些情况下是否抛出异常的信息.如果它也不这样做,那么我想这个问题的第二部分是多余的。
如果是,那么 "correct" 处理 file.close()
方法在用于打开文件的 "with" 语句中抛出异常的方法是什么?
是否存在文件打开并成功读取后file.close()
会立即失败的情况?
您可以使用
file object = open(file_name [, access_mode][, buffering])
然后你检查
file.closed
如果文件已关闭,则为 return 真,否则为假。
close
可以抛出异常,例如,如果您 运行 磁盘 space 试图刷新您的最后一次写入,或者如果您拔出 USB 记忆棒文件已打开。
至于如何正确处理这个问题,这取决于您的应用程序的细节。也许您想向用户显示一条错误消息。也许你想关闭你的程序。也许您想重试您正在做的任何事情,但使用不同的文件。无论您选择哪种响应,它都可能会在您的程序最适合处理它的任何层中使用 try
-except
块来实现。
是的,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()
函数的非零 return 值导致 Python 引发 IOError
异常。
如果您想处理这个异常,请在 with
语句 周围放置一个 try...except
块 :
try:
with open(filename, mode) as fileobj:
# do something with the open file object
except IOError as exc:
# handle the exception
当然,IOError
也可能是在 开启 时抛出的。