Created
February 10, 2022 21:07
-
-
Save potat-dev/47e14bad12cdbfd3da3dc1b9629141c4 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 smart_rename(file): | |
# renames a file by adding a numeric index to it | |
# increments the index if the directory already has files with the index | |
regex = r'(.+)_\((\d+)\)\.(.+)' # filename_(0).ext | |
make_filename = lambda p: p[0] + f"_({p[1]})." + p[2] | |
filename, path = os.path.basename(file), os.path.dirname(file) | |
match = match_regex(regex, filename) | |
parts = list(match.groups())[::2] if match else filename.split('.') | |
parts.insert(1, int(match.group(2)) if match else 0) | |
new_path = os.path.join(path, make_filename(parts)) | |
while os.path.exists(new_path): | |
parts[1] += 1 | |
new_path = os.path.join(path, make_filename(parts)) | |
return new_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment