0

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?

falco
  • 145
  • 2
  • 11
  • Get the highest number of the names of the directories, add 1, create new directory? – sloth Feb 11 '15 at 12:38
  • 1
    Really, your question should be more specific. Do you have problems reading the directory names? Extracting the number from a filename? Creating a new directory? – sloth Feb 11 '15 at 12:39
  • i'm just new to prog...your logic sounds right, thnx – falco Feb 11 '15 at 12:42
  • It is often helpful to include your code. What have you tried, what were the results, what specific problems are you facing, etc. – noshelter Feb 11 '15 at 12:58

3 Answers3

1

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

StenSoft
  • 8,919
  • 20
  • 27
0

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

Community
  • 1
  • 1
Paul
  • 5,079
  • 5
  • 34
  • 49
0

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