Skip to content

Instantly share code, notes, and snippets.

@CzBiX
Last active Sep 2, 2015
Embed
What would you like to do?
batch rename files with regex
#!/usr/bin/env python3
import errno
__author__ = 'czbix'
import argparse
import os
import re
import glob
def main():
args = parse_arg()
path = args.path
src_regex = re.compile(args.src_regex)
dst_regex = args.dst_regex
is_real = args.is_real
files = glob.glob(path)
if len(files) > 0:
for name in files:
rename_file(name, src_regex, dst_regex, is_real)
if is_real:
print("Files renamed.")
return
print("path not found: " + path)
return errno.ENOENT
def rename_file(name, src_regex, dst_regex, is_real):
new_name = src_regex.sub(dst_regex, name)
if new_name == name:
return
print("%s -> %s" % (name, new_name))
if is_real:
os.rename(name, new_name)
def parse_arg():
"""
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description="batch rename files with regex")
parser.add_argument('path', help='the path of file or dir')
parser.add_argument('src_regex', help='regex to match')
parser.add_argument('dst_regex', help='regex to instead of')
parser.add_argument('-f', action='store_true', dest='is_real',
help='do rename action, default action is print info only')
return parser.parse_args()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment