Skip to main content
 首页 » 编程设计

python之如何在 python 中使用循环创建多个目录

2024年10月01日7findumars

我想用一个循环创建 10 个目录,我试过这段代码:

import os 
pathname = 1 
directory = "C:\Directory\Path\Name\\" + str(pathname) 
 
 
while pathname < 11: 
    if not os.path.exists(directory): 
        os.makedirs(directory) 
    pathname += 1   

但它只是创建第一个目录并停止,就好像它甚至没有经历循环的其余部分一样。我是 python 的新手,这段代码对我来说很有意义,但我不知道为什么它可能不会work.Any帮助表示赞赏。

请您参考如下方法:

import os 
pathname = 1 
directory = "C:\Directory\Path\Name\\" + str(pathname) 
 
while pathname < 11: 
    if not os.path.exists(directory): 
        os.makedirs(directory) 
    pathname += 1   
    directory = "C:\Directory\Path\Name\\" + str(pathname)