Skip to content

Instantly share code, notes, and snippets.

@nkrh
Created January 19, 2018 09:03
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nkrh/d14dcd37f3c5c9f81e10b2aa2f23bd54 to your computer and use it in GitHub Desktop.
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