python-明确处理文件存在异常

2024-04-26 04:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这个论坛上遇到过这样的例子:通过测试OSError(或者现在的IOError)中的errno值来处理文件和目录的特定错误。例如,这里的一些讨论-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.'

如何具体检查此错误和类似的其他错误?


Tags: 文件目录for错误notopen论坛例子
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)

根据代码print ...,您似乎正在使用Python 2.x.^{}是在Python 3.3中添加的;您不能使用FileExistsError

使用^{}

import os
import errno

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

相关问题 更多 >

    热门问题