繁体   English   中英

Python创建目录失败

[英]Python create directory failing

我正在使用一些非常标准的代码:

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

我删除目录,然后将检查从1拖放到2 我超出了这一步,并在3处出现了错误消息。

但是,当我检查时,目录已成功创建。

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

我想念什么?

os.makedirs不会通过返回值指示是否成功:它始终返回None

NoneFalse -y,因此not os.makedirs(args.outputDirectory, 0o666)始终not os.makedirs(args.outputDirectory, 0o666) True ,这会触发sys.exit代码路径。


幸运的是,您不需要任何这些。 如果os.makedirs失败,它将抛出OSError

您应该捕获异常,而不是检查返回值:

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

如果未引发OSError ,则表明目录已成功创建。

您不需要调用os.path.exists() (或os.path.isdir() ); os.makedirs()具有exist_ok参数。

正如@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))

注意:与基于os.path.exist()的解决方案不同; 如果路径存在但它不是目录(或目录的符号链接),则会引发错误。

mode参数可能存在问题, 请参阅3.4.1之前的Python版本说明

暂无
暂无

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

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