Last active
September 2, 2015 03:39
-
-
Save CzBiX/2c059f9cd0bcd88eff94 to your computer and use it in GitHub Desktop.
batch rename files with regex
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
#!/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