Python创建目录失败

2024-09-30 07:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 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处找到了错误消息。在

然而,当我成功地创建了这个目录时。在

^{pr2}$

我错过了什么??在


Tags: path代码目录output标准ifosexists
2条回答

os.makedirs不通过返回值指示是否成功:它总是返回None。在

NoneFalse-y,因此,not os.makedirs(args.outputDirectory, 0o666)总是{},这会触发你的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()有{}参数。在

as @Thomas Orozco mentioned,则不应检查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参数see the note for versions of Python before 3.4.1可能有问题

相关问题 更多 >

    热门问题