简体   繁体   中英

Python create incremental folders

I'm trying to create a script that will create a one folder every time I run the script. I want the name to end in a number that increases up by 1. So, run once gets me folder1, run again gets me folder2 and so on. My current code runs once and create folder1 and folder2, after that every run creates a single folder like i want. Why is the first run making 2 folders?

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)

This happens because because your code actually looks like this with the unnecessary variables removed:

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)

As you can see the 'request1' folder is created on the first program run, then goes on to function normally. This is easy to fix, just remove the first if statement:

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)

I would remove the extra brackets to improve readability and use f-strings if you can eg mypath = f'C:/Users/jh/Desktop/request{counter}/'

The first time it runs, it checks to see if the path exists, it does not - so it creates the directory as expected.

Then the program continues, and checks to see if it exists again (it does, because you just created it), and creates #2.

You might want to switch this to if/else.

This is because on first run your base path doesn't exist so it creates one. Further in while loop it again loops over and creates another folder. For all subsequent runs the first if condition is always false so it creates only one folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM