Last active
December 17, 2022 07:47
-
-
Save nodewee/9ae9b0b461b4bcaf30bc2b84ca8c4743 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def auto_rename_exist_filename(file_path): | |
""" | |
For example: a.txt, a(1).txt, a(2).txt | |
Source: https://gist.github.com/nodewee/9ae9b0b461b4bcaf30bc2b84ca8c4743.js | |
""" | |
if not os.path.exists(file_path): | |
return file_path | |
dir_path = os.path.dirname(file_path) | |
src_filename = os.path.basename(file_path) | |
[file_title, ext_name] = os.path.splitext(src_filename) | |
pattern = r"\((\d+?)\)$" | |
r = re.search(pattern, file_title) | |
if r: | |
serial = str(int(r.groups()[0]) + 1) | |
new_title = re.sub(pattern, "(" + serial + ")", file_title) | |
else: | |
new_title = file_title + "(1)" | |
new_filepath = os.path.join(dir_path, new_title + ext_name) | |
if os.path.exists(new_filepath): | |
return auto_rename_exist_filename(new_filepath) | |
else: | |
return new_filepath |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment