Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rename files with Python
@ECHO OFF
SET PATTERN=%1
SET REPLACE=%2
python %~dp0/regex_rename.py %PATTERN% %REPLACE%
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