Skip to content

Instantly share code, notes, and snippets.

@highfestiva
Last active November 3, 2023 15:08
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 highfestiva/a8a685ce048e23f9c3d19ddbe7a38258 to your computer and use it in GitHub Desktop.
Save highfestiva/a8a685ce048e23f9c3d19ddbe7a38258 to your computer and use it in GitHub Desktop.
Recursively rename multiple files
#!/usr/bin/env python3
import glob
import os
import re
import sys
def printUsage():
print("%s <wildcard> <replacement wildcard>" % sys.argv[0])
print("Example: %s * Ui*" % sys.argv[0])
print("Only one asterisk may be used in the wildcards.")
def renameFiles(target_dir, wildcard, replacement):
wildcardRegex = wildcard.replace('.', '\\.').replace('*', '(.*)')
replacementRegex = replacement.replace('*', '\\1')
infiles = glob.glob(target_dir + '/' + wildcard)
for infile in infiles:
outfile = re.sub(wildcardRegex, replacementRegex, infile);
print(infile, "->", outfile)
os.rename(infile, outfile)
def main():
if len(sys.argv) == 3:
wildcardList = sys.argv[1].split("*")
replacementList = sys.argv[2].split("*")
if len(wildcardList) == 2 and len(replacementList) == 2:
for root,ds,files in os.walk('.'):
for d in ds:
td = root + '/' + d
renameFiles(td, "*".join(wildcardList), "*".join(replacementList))
else:
printUsage()
else:
printUsage();
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment