当目录不存在时,os.mkdir(path)返回OSError [英] os.mkdir(path) returns OSError when directory does not exist

查看:263
本文介绍了当目录不存在时,os.mkdir(path)返回OSError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在呼叫os.mkdir,以使用一组特定的生成数据来创建文件夹.但是,即使尚未创建我指定的路径,os.mkdir(path)也会引发该路径已存在的OSError.

I am calling os.mkdir to create a folder with a certain set of generated data. However, even though the path I specified has not been created, the os.mkdir(path) raises an OSError that the path already exists.

例如,我致电:

os.mkdir(test)

即使我在任何地方都没有测试目录或名为test的文件,此调用也会导致OSError: [Errno 17] File exists: 'test'.

This call results in OSError: [Errno 17] File exists: 'test' even though I don't have a test directory or a file named test anywhere.

注意:我使用的实际路径名不是"test",而是更确定的东西,我确定它没有在任何地方命名.

NOTE: the actual path name I use is not "test" but something more obscure that I'm sure is not named anywhere.

请帮助?

推荐答案

Greg的回答是正确的,但还远远不够. OSError具有子错误条件,并且您不想每次都抑制它们.谨慎地仅捕获预期操作系统错误.

Greg's answer is correct but doesn't go far enough. OSError has sub-error conditions, and you don't want to suppress them all every time. It's prudent to trap just expected OS errors.

在决定抑制异常之前,请进行其他检查,如下所示:

Do additional checking before you decide to suppress the exception, like this:

import errno
import os

try:
    os.mkdir(dirname)
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise
    pass

您可能不想隐藏errno.EACCES(权限被拒绝),errno.ENOSPC(设备上没有剩余空间),errno.EROFS (只读文件系统)等.也许您确实想要-但这需要根据您所构建内容的特定逻辑做出有意识的决定.

You probably don't want to suppress errno.EACCES (Permission denied), errno.ENOSPC (No space left on device), errno.EROFS (Read-only file system) etc. Or maybe you do want to -- but that needs to be a conscious decision based on the specific logic of what you're building.

Greg的代码抑制了所有操作系统错误;就像except Exception是不安全的一样.

Greg's code suppresses all OS errors; that's unsafe just like except Exception is unsafe.

这篇关于当目录不存在时,os.mkdir(path)返回OSError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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