简体   繁体   English

Python创建目录失败

[英]Python create directory failing

I am using some pretty standard code: 我正在使用一些非常标准的代码:

 1   if not os.path.exists(args.outputDirectory):
 2       if not os.makedirs(args.outputDirectory, 0o666):
 3           sys.exit('Fatal: output directory "' + args.outputDirectory + '" does not exist and cannot be created')

I remove the directory and the check at 1 drops through to 2 . 我删除目录,然后将检查从1拖放到2 I one-step beyond that and hit the error message at 3 . 我超出了这一步,并在3处出现了错误消息。

However, when I check, the directory was created successfully. 但是,当我检查时,目录已成功创建。

drwxrwsr-x 2 userId userGroup  4096 Jun 25 16:07 output/

What am I missing?? 我想念什么?

os.makedirs does not indicate whether it succeeded through its return value: it always returns None . os.makedirs不会通过返回值指示是否成功:它始终返回None

None is False -y, therefore, not os.makedirs(args.outputDirectory, 0o666) is always True , which triggers your sys.exit code path. NoneFalse -y,因此not os.makedirs(args.outputDirectory, 0o666)始终not os.makedirs(args.outputDirectory, 0o666) True ,这会触发sys.exit代码路径。


Fortunately, you don't need any of that. 幸运的是,您不需要任何这些。 If os.makedirs fails, it'll throw an OSError . 如果os.makedirs失败,它将抛出OSError

You should catch the exception, not check the return value: 您应该捕获异常,而不是检查返回值:

try:
    if not os.path.exists(args.outputDirectory):
        os.makedirs(args.outputDirectory, 0o666):
except OSError:
    sys.exit('Fatal: output directory "' + args.outputDirectory + '" does not exist and cannot be created')

If no OSError is thrown, that means the directory was successfully created. 如果未引发OSError ,则表明目录已成功创建。

You don't need to call os.path.exists() (or os.path.isdir() ); 您不需要调用os.path.exists() (或os.path.isdir() ); os.makedirs() has exist_ok parameter. os.makedirs()具有exist_ok参数。

And as @Thomas Orozco mentioned , you shouldn't check os.makedirs() ' return value because os.makedirs() indicates errors by raising an exception instead: 正如@Thomas Orozco所述 ,您不应该检查os.makedirs()的返回值,因为os.makedirs()通过引发异常来指示错误:

try:
    os.makedirs(args.output_dir, mode=0o666, exist_ok=True)
except OSError as e:
    sys.exit("Can't create {dir}: {err}".format(dir=output_dir, err=e))

Note: Unlike os.path.exist() -based solution; 注意:与基于os.path.exist()的解决方案不同; it raises an error if the path exists but it is not a directory (or a symlink to a directory). 如果路径存在但它不是目录(或目录的符号链接),则会引发错误。

There could be issues with the mode parameter, see the note for versions of Python before 3.4.1 mode参数可能存在问题, 请参阅3.4.1之前的Python版本说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM