【问题标题】:python - specifically handle file exists exceptionpython - 专门处理文件存在异常
【发布时间】:2013-12-26 20:01:27
【问题描述】:

我在这个论坛中遇到过一些示例,其中通过测试 OSError 中的 errno 值来处理文件和目录的特定错误(或者这些天是 IOError ?)。例如,这里的一些讨论 - Python's "open()" throws different errors for "file not found" - how to handle both exceptions?。但是,我认为,这不是正确的方法。毕竟,FileExistsError 的存在是为了避免担心errno

以下尝试没有成功,因为我收到了令牌 FileExistsError 的错误。

try:
    os.mkdir(folderPath)
except FileExistsError:
    print 'Directory not created.'

您如何专门检查此错误和类似的其他错误?

【问题讨论】:

标签: python exception ioerror


【解决方案1】:

根据代码print ...,您似乎使用的是 Python 2.x。在 Python 3.3 中添加了FileExistsError;你不能使用FileExistsError

使用errno.EEXIST:

import os
import errno

try:
    os.mkdir(folderPath)
except OSError as e:
    if e.errno == errno.EEXIST:
        print('Directory not created.')
    else:
        raise

【讨论】:

  • 所以,从 Python 3.3 开始,我可以使用 FileExistsError。谢谢!
【解决方案2】:

这是一个在尝试atomically overwrite an existing symlink 时处理竞争条件的示例:

# os.symlink requires that the target does NOT exist.
# Avoid race condition of file creation between mktemp and symlink:
while True:
    temp_pathname = tempfile.mktemp()
    try:
        os.symlink(target, temp_pathname)
        break  # Success, exit loop
    except FileExistsError:
        time.sleep(0.001)  # Prevent high load in pathological conditions
    except:
        raise
os.replace(temp_pathname, link_name)

【讨论】:

    猜你喜欢
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多