falco
falco

Reputation: 165

Create a new directory each time a Python program is executed

i need to create a new directory in my Python program, each time it is executed. For example, if it is executed the first time, the directory

C:\Users\person\Desktop\Test_1

is created

If it is executed for the second time, the directory

C:\Users\person\Desktop\Test_2

is created

and so on. How can this be achieved?

Upvotes: 0

Views: 264

Answers (3)

Rahul Bhat
Rahul Bhat

Reputation: 113

Here is how you do it.

import os

root=r'/your/root/dir/here' #insert your directory where you want the new directory to be present

dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root,item)) ] 
 #has the list containing all the folder names

x=list(max(dirlist)) #finds the max number in the list and converts it into a list
y=x[-1]=int(x[-1])+int(('1')) #takes the last digit and adds one
path=r'/your/root/dir/here/test'+format(y) # make sure you have a folder already with a name test
os.makedirs(path, exist_ok=True) #creates a new dir everytime with max number

Upvotes: 0

Paul
Paul

Reputation: 6767

First and most simple way is just parse dir structure, get the last number of index and and than create new directory with new index.

If you are not familiar with creating directories, this topic will be useful for you: How to check if a directory exists and create it if necessary?

Also os.path is your best friend here: https://docs.python.org/2/library/os.path.html#module-os.path

Upvotes: 0

StenSoft
StenSoft

Reputation: 9617

Find all directories starting with Test_, find the one with the highest number, add 1 and create a new directory.

Upvotes: 1

Related Questions