Last active
April 27, 2020 17:44
-
-
Save yammesicka/57731fe87a8bce5c9b7a81bd1a2bc424 to your computer and use it in GitHub Desktop.
Mass filename changer (using regex, case sensitivity included)
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
from functools import partial | |
from pathlib import Path | |
import re | |
REGEX_REPLACE = 'cow' | |
PATH = r'C:\Users\Yam' | |
DRY = False | |
def change_filename(before: Path, after: Path, dry: bool) -> bool: | |
if before != after: | |
print(f"{before} -> {after}") | |
if not dry: | |
before.rename(after) | |
return True | |
return False | |
def remove_from_filename( | |
to_remove: str, | |
filepath: Path, | |
case_sensitive: bool = False, | |
dry: bool = False, | |
) -> bool: | |
flags = 0 if case_sensitive else re.IGNORECASE | |
replacer = re.compile(f'{to_remove}', flags) | |
new_path = filepath.parent / replacer.sub('', filepath.name) | |
return change_filename(filepath, new_path, dry) | |
remove_regex_from_filename = partial(remove_from_filename, REGEX_REPLACE) | |
files = Path(PATH).glob('*') | |
count = sum(remove_regex_from_filename(file) for file in files) | |
print(f"Total of {count} file changed.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment