Python:使用 os.mkdir 创建文件夹并使用方括号时出现 WindowsError

Python: WindowsError when creating folder with os.mkdir and using square brackets

在 Windows,当我尝试创建以下文件夹时:

    os.mkdir('H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW')

我收到错误:

WindowsError: [Error 3] The system cannot find the path specified: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS. Original CRW'

“_NEW”文件夹已经存在,它是当前工作目录。然后我尝试使用单反斜杠:

os.mkdir('H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS. Original CRW')

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\x01. Original CRW'

因此“\1”被转换为“\x01”。像以前一样转义这个特殊的反斜杠会导致 [Error 3] 错误。

使字符串成为字符串文字:

os.mkdir(r'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS. Original CRW')

产生了同样的错误:

WindowsError: [Error 3] The system cannot find the path specified: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS. Original CRW'

然后:

os.mkdir("H:\[ Photo sorting process ]\NEW")

不好(“[照片排序过程]”不存在),但是:

os.mkdir("H:\[ Photo sorting process ]")
os.mkdir("H:\[ Photo sorting process ]\NEW")

很好。这是否意味着我只能创建 1 级子目录?还有别的办法吗?我想将路径作为变量传递。

您可以使用 os.makedirs 而不是 os.mkdir。来自文档:

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.