0

I have files in directory in following order :

COL_1001.png
COL_1002.png

the next time I save a file i want it to be saved as

COL_1003.png

How can I do this using python program as I am using shutil as given in the example

    allfiles = os.listdir(src)
    
    c = 1001
    for f in allfiles:
        if f in files and len(selected_prop)>0:
            s = f
            s = f.split('.')
            s[0] = projCode + '_' + selected_prop[0] + '_COL.' + str(c)
            k = '.'.join(s)
            shutil.copy( src + '\\' + f, os.path.join(dst,k))
            c += 1

Thanks

Kartikey

  • Please edit your question and include all the code to create minimal working example. For example: `if f in files and len(selected_prop)>0:` What is `files` and `selected_prop`? – Cow Jan 09 '23 at 12:51

1 Answers1

1

pathlib is much simpler to use than os. With a bit of regex you can do it.

import re
from pathlib import Path
from typing import Union


def get_next_name(dirpath: Union[Path, str]) -> str:
    """Finds the next name available in the directory supplied."""
    filename_pattern = re.compile(r"COL_(\d+).png")
    filename_template = "COL_{}.png"
    minimum_number = 1001 - 1  # for the first to be 1001
    filenames_in_directory = tuple(
        dir_entry.name
        for dir_entry in Path(dirpath).iterdir()
        if dir_entry.is_file()
    )
    filename_matches = tuple(
        filename_match
        for filename_match in map(filename_pattern.fullmatch, filenames_in_directory)
        if filename_match
    )
    numbers_matches = tuple(
        int(filename_match.group(1))
        for filename_match in filename_matches
    )
    next_number = max(
        (minimum_number, *numbers_matches)
    ) + 1
    return filename_template.format(next_number)


name = get_next_name(".")
print(name)
Path(name).touch()
name = get_next_name(".")
print(name)
Path(name).touch()
name = get_next_name(".")
print(name)
Path(name).touch()
Lenormju
  • 4,078
  • 2
  • 8
  • 22