os.mkdir错误 - 系统无法找到指定的路径

RSh*_*hah 5 mkdir python-2.7

我正在尝试使用字典键创建新文件夹.代码是:

os.mkdir("Y:\\Bleeding-study\\MIMIC\\Notes\\randombins\\")

for key in index:
    os.mkdir("Y:\\Bleeding-study\\MIMIC\\Notes\\randombins\\batch_%s\\"%str(key))
    os.mkdir("Y:\\Bleeding-study\\MIMIC\\Notes\\randombins\\batch_%s\\%s\\"%(str(key),"config"))
    os.mkdir("Y:\\Bleeding-study\\MIMIC\\Notes\\randombins\\batch_%s\\corpus\\"%str(key))
Run Code Online (Sandbox Code Playgroud)

错误是:
WindowsError: [Error 3] The system cannot find the path specified: 'Y:\\Bleeding-study\\MIMIC\\Notes\\randombins\\batch_0\\'

我认为这段代码会创建该文件路径名,那为什么会出现这个错误呢?

SiH*_*iHa 14

您的错误是因为您尝试在一个步骤中创建多个级别的目录. os.mkdir()只会创建一个级别的目录,因此该行失败:

os.mkdir("Y:\\Bleeding-study\\MIMIC\\Notes\\randombins\\batch_%s\\"%str(key))因为您尚未创建batch_0目录.

os.makedirs() 这就是你需要的:

递归目录创建功能.像mkdir()一样,但是需要包含叶子目录的所有中间级目录.
...

...事实上,如果你使用它,那么你可以取消初始os.mkdir(),因为它将是多余的.