python - Python 中 with 语句中的 file.close() 异常处理

标签 python python-3.x file-handling

我知道在 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 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() 函数的非零返回值导致 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/

相关文章:

python - 如何使用极坐标绘制 scipy.hierarchy.dendrogram?

python - 在本地设置 Bluemix VCAP_SERVICES 环境变量以便我可以在本地进行开发?

c++ - getline() 函数在 while 循环中不起作用

python-3.x - 似乎找不到 .pyc 文件?

c++ - 如何在 C++ 中对文本文件进行排序

C - 使用文件处理和链表登录

python - 导入 Keras 层时出错

python - 如何为多个数据框列制作管道?

python - Asyncio Pandas 与 Inplace

Python 字符串拆分返回奇怪的字符