0

I am writing a script to save some images in a folder each time it runs. I would like make a new folder each it runs with a enumerating folder names. for example if I run it first time , it just save the images in C:\images\folder1 and next time I run it, it will save the images in C:\images\folder2 and C:\images\folder3 and so on.

And if I delete these folders, and start running again, it would start from the "C:\images\folder1" again.

I found this solution works for file names but not for the folder names: Create file but if name exists add number

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

I feel like you could do something by getting a list of the directories and then looping over numbers 1 to n for the different possible directories until one can't be found.

from pathlib import Path
import os 

path = Path('.')
folder = "folder"
i = 1

dirs = [e for e in path.iterdir() if e.is_dir()]

while True:
    if folder+str(i) not in dirs:
        folder = folder+str(i)
        break
    i = i+1
os.mkdir(folder)

I'm sorry if I made any typos, but that seems like a way that should work.

Patrick Gorman
  • 132
  • 1
  • 8
1

The pathlib library is the standard pythonic way of dealing with any kind of folders or files and is system independent. As far as creating a new folder name, that could be done in a number of ways. You could check for the existence of each file (like Patrick Gorman's answer) or you could save a user config file with a counter that keeps track of where you left off or you could recall your file creation function if the file already exists moving the counter. If you are planning on having a large number of sub-directories (millions), then you might consider performing a binary search for the next folder to create (instead of iterating through the directory).

Anyway, in windows creating a file/folder with the same name, adds a (2), (3), (4), etc. to the filename. The space and parenthesis make it particularly easy to identify the number of the file/folder. If you want the number directly appended, like folder1, folder2, folder3, etc., then that becomes a little tricky to detect. We essentially need to check what the folder endswith as an integer. Finding particular expressions within in a tricky string is normally done with re (regular expressions). If we had a space and parenthesis we probably wouldn't need re to detect the integer in the string.

from pathlib import Path
import re

def create_folder(string_or_path):
    path = Path(string_or_path)
    if not path.exists(): 
        #You can't create files and folders with the same name in Windows. Hence, check exists. 
        path.mkdir() 
    else:
        #Check if string ends with numbers and group the first part and the numbers. 
        search = re.search('(.*?)([0-9]+$)',path.name) 
        if search:
            basename,ending = search.groups()
            newname = basename + str(int(ending)+1)
        else:
            newname = path.name + '1'
        create_folder(path.parent.joinpath(newname))

path = Path(r'C:\images\folder1')
create_folder(path) #creates folder1
create_folder(path) #creates folder2, since folder1 exists
create_folder(path) #creates folder3, since folder1 and 2 exist
path = Path(r'C:\images\space')
create_folder(path) #creates space
create_folder(path) #creates space1, since space exists

Note: Be sure to use raw-strings when dealing with windows paths, since "\f" means something in a python string; hence you either have to do "\\f" or tell python it is a raw-string.

Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15