Python - 专门处理文件存在异常

31

我在这个论坛中遇到了一些示例,处理文件和目录的特定错误是通过测试 OSError 中的 errno 值来处理的(现在也可能是 IOError)。例如,在这里有一些讨论 - Python 的 "open()" 对于 "file not found" 抛出不同的错误 - 如何处理这两个异常?。但我认为,那不是正确的方法。毕竟,FileExistsError 存在是为了避免担心 errno

以下尝试失败了,因为我得到了一个关于令牌 FileExistsError 的错误。

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

你如何特别检查这种错误和类似的其他错误?


2
假定您使用的是2.7版本,那么在Python中,FileExistsError并不是内置的异常。请在此处查看完整的内置异常列表: http://docs.python.org/2/library/exceptions.html#module-exceptions 据我所见,您应该使用类似于"IOError"的东西来处理这个问题。 - Dyrborg
2个回答

48
根据代码print ...,看起来你正在使用Python 2.x版本。FileExistsError是在Python 3.3中添加的,你不能使用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

1
所以,从Python 3.3开始,我可以使用FileExistsError。谢谢! - cogitoergosum

3
下面是处理竞争条件的示例,当尝试以原子方式覆盖现有符号链接时:

# 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)

除了:提高。好东西:D - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接