【问题标题】:Python create directory failingPython创建目录失败
【发布时间】:2015-06-25 14:13:25
【问题描述】:

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

 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/

我错过了什么??

【问题讨论】:

  • 旁白:使用if os.path.isdir(...) 可能比if os.path.exists(...) 更好。如果预期的目录名称已作为常规文件存在,您的代码将产生意想不到的结果。

标签: python python-3.x mkdirs


【解决方案1】:

os.makedirs通过其返回值并不表示是否成功:它总是返回None

NoneFalse-y,因此,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,则表示目录创建成功。

【讨论】:

  • 由于某种原因,将访问模式作为参数传递给makedirs没有生效。该目录是信条,但不是所需的模式。我添加了以下os.chmod(args.outputDirectory, 0o666),效果很好(Python 3.2)。
【解决方案2】:

您无需致电os.path.exists()(或os.path.isdir()); os.makedirs()exist_ok 参数。

还有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 可能存在问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多