我使用了一些非常标准的代码:
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}$我错过了什么??在
os.makedirs
不通过返回值指示是否成功:它总是返回None
。在None
是False
-y,因此,not os.makedirs(args.outputDirectory, 0o666)
总是{sys.exit
代码路径。在幸运的是,你不需要这些。如果
os.makedirs
失败,它将抛出一个OSError
。在您应该捕获异常,而不是检查返回值:
如果没有抛出
OSError
,则表示目录已成功创建。在您不需要调用}参数。在
os.path.exists()
(或os.path.isdir()
);os.makedirs()
有{而as @Thomas Orozco mentioned,则不应检查
os.makedirs()
'返回值,因为os.makedirs()
通过引发异常来指示错误:注意:与基于
os.path.exist()
的解决方案不同,如果路径存在但不是目录(或指向目录的符号链接),则会引发错误。在mode
参数see the note for versions of Python before 3.4.1可能有问题相关问题 更多 >
编程相关推荐