Created
January 19, 2018 09:03
-
-
Save nkrh/d14dcd37f3c5c9f81e10b2aa2f23bd54 to your computer and use it in GitHub Desktop.
Rename files with Python
This file contains hidden or 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
@ECHO OFF | |
SET PATTERN=%1 | |
SET REPLACE=%2 | |
python %~dp0/regex_rename.py %PATTERN% %REPLACE% |
This file contains hidden or 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
import argparse, os, re | |
parser = argparse.ArgumentParser() | |
parser.add_argument('pattern', help='File pattern you looking for') | |
parser.add_argument('replace', help='New file name pattern') | |
args = parser.parse_args() | |
path = os.curdir | |
replace = args.replace | |
comp = re.compile(args.pattern) | |
for f in os.listdir(path): | |
full_path = os.path.join(path, f) | |
if os.path.isfile(full_path): | |
match = comp.search(f) | |
if not match : | |
continue | |
try: | |
new_name = match.expand(replace) | |
new_name = os.path.join(path, new_name) | |
except re.error: | |
continue | |
if os.path.isfile(new_name): | |
print('%s -> %s skipped' % (f, new_name)) | |
else: | |
os.rename(full_path, new_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment