Python创建增量文件夹

Python创建增量文件夹,python,directory,Python,Directory,我正在尝试创建一个脚本,该脚本将在每次运行脚本时创建一个文件夹。我希望名称以增加1的数字结尾。所以,跑一次得到我的folder1,再跑一次得到我的folder2,依此类推。我当前的代码运行一次并创建folder1和folder2,然后每次运行都会创建一个我想要的文件夹。为什么第一次运行要创建两个文件夹 import os counter = 1 mypath =. ('C:/Users/jh/Desktop/request'+(str(counter)) +'/') if not os

我正在尝试创建一个脚本,该脚本将在每次运行脚本时创建一个文件夹。我希望名称以增加1的数字结尾。所以,跑一次得到我的folder1,再跑一次得到我的folder2,依此类推。我当前的代码运行一次并创建folder1和folder2,然后每次运行都会创建一个我想要的文件夹。为什么第一次运行要创建两个文件夹

import os

counter = 1
mypath =.     ('C:/Users/jh/Desktop/request'+(str(counter)) +'/')
if not os.path.exists(mypath):
    os.makedirs(mypath)
    print ("Path is created")

while os.path.exists(mypath):   
    counter +=1
    mypath = ('C:/Users/jh/Desktop/request'+(str(counter)) +'/')
   print(mypath)

os.makedirs(mypath)

之所以会出现这种情况,是因为您的代码实际上是这样的,并且删除了不必要的变量:

import os

counter = 1
mypath = 'C:/Users/jh/Desktop/request1/'
if not os.path.exists(mypath):
    os.makedirs(mypath)
    print ("Path is created")

while os.path.exists(mypath):   
    counter += 1
    mypath = 'C:/Users/jh/Desktop/request'+(str(counter)) +'/'
    print(mypath)

os.makedirs(mypath)
正如您所见,“request1”文件夹是在第一次程序运行时创建的,然后继续正常运行。这很容易修复,只需删除第一条if语句:

import os

counter = 1
mypath = 'C:/Users/jh/Desktop/request1/'

while os.path.exists(mypath):   
    counter += 1
    mypath = 'C:/Users/jh/Desktop/request'+(str(counter)) +'/'
    print(mypath)

os.makedirs(mypath)
如果可以的话,我会删除额外的括号以提高可读性,并使用f字符串。
mypath=f'C:/Users/jh/Desktop/request{counter}/'

它第一次运行时,会检查路径是否存在,因此会按预期创建目录

然后程序继续,检查它是否再次存在(确实存在,因为您刚刚创建了它),并创建#2


您可能希望将其切换到if/else。

这是因为在第一次运行时,您的基本路径不存在,所以它会创建一个。在
循环中,它再次循环并创建另一个文件夹。对于所有后续运行,第一个
if
条件始终为false,因此它只创建一个文件夹