Skip to content

Instantly share code, notes, and snippets.

@ILikePizza555
Created September 8, 2016 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ILikePizza555/881ef057448b88273a9cd17b3f4101f7 to your computer and use it in GitHub Desktop.
Save ILikePizza555/881ef057448b88273a9cd17b3f4101f7 to your computer and use it in GitHub Desktop.
Simple python utility that renames files in bulk using regex
import os
import sys
import argparse
import re
parser = argparse.ArgumentParser(description="Rename some files.")
parser.add_argument("path", type=str, help="Path to work on.")
parser.add_argument("text", type=str, help="Text to replace with.")
parser.add_argument("-e", "--enumerate", action="store_true", dest="enumerate", help="Add a number at the end of a file name.")
parser.add_argument("-r", "--regex", dest="regex", help="Runs all filenames against provided regex, then changes matches (if any) to provided text.", default="[\s\S]*")
if __name__ == "__main__":
args = vars(parser.parse_args())
prog = re.compile(args["regex"])
for num, file in enumerate(os.listdir(args["path"])):
#Make sure we don't overwrite ourselves
if file != os.path.basename(__file__):
repl = args["text"] + str(num) if args["enumerate"] else ""
old_name = os.path.join(args["path"], file)
new_name = os.path.join(args["path"], re.sub(prog, repl, file))
print("Renaming {} to {}".format(old_name, new_name))
os.rename(old_name, new_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment