python-专门处理文件存在异常 [英] python - specifically handle file exists exception

查看:178
本文介绍了python-专门处理文件存在异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个论坛上遇到过一些示例,其中通过测试 OSError errno 值来处理围绕文件和目录的特定错误。 c $ c>(或这些天 IOError 吗?)。例如,此处的一些讨论- Python的 open()对找不到文件抛出不同的错误。 -如何处理这两种异常?。但是,我认为这不是正确的方法。毕竟,存在 FileExistsError 专门用于避免担心 errno

I have come across examples in this forum where a specific error around files and directories is handled by testing the errno value in OSError (or IOError these days ?). For example, some discussion here - Python's "open()" throws different errors for "file not found" - how to handle both exceptions?. But, I think, that is not the right way. After all, a FileExistsError exists specifically to avoid having to worry about errno.

以下尝试没有成功,因为令牌 FileExistsError 出现错误。

The following attempt didn't work as I get an error for the token FileExistsError.

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

如何检查此错误以及其他类似的错误?

How do you check for this and similar other errors specifically ?

推荐答案

根据代码 print ... ,看来您正在使用Python2.x。 FileExistsError 是在Python 3.3中添加;您不能使用 FileExistsError

According to the code print ..., it seems like you're using Python 2.x. FileExistsError was added in Python 3.3; You can't use 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-专门处理文件存在异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆