Skip to content

Instantly share code, notes, and snippets.

@elusive
Created May 11, 2019 05:08
Show Gist options
  • Save elusive/76776b6d407a7aa1b4eac579c2ef4f3f to your computer and use it in GitHub Desktop.
Save elusive/76776b6d407a7aa1b4eac579c2ef4f3f to your computer and use it in GitHub Desktop.
Simple python script to rename a directory of files using regex pattern.
#!/usr/bin/env python
####################
# file_renamer.py
# [email protected]
#
import os, glob, re
i = 0
## search substring to replace
pattern = "wp-content\\\\uploads\\\\"
## replace with...
replacement = ""
## folder to look in for file pattern
base_path = "/home/jogi/Projects/elusive.github.io/assets/images/"
## loop through files found by pattern
for pathname in glob.glob(base_path + "wp-content\\uploads\\*.*"):
# PATHNAME
print("pathname =", pathname) ## TEST OUTPUT
## BASENAME
basename = os.path.basename(pathname)
#print("basename =", basename) ## TEST OUTPUT
## CALCULATE NEW FILENAME WITH REGULAR EXPRESSIONS
NewFilename = re.sub(pattern, replacement, pathname)
print("new-file-name = ", NewFilename) ## TEST OUTPUT
## Change the name
os.rename(pathname, NewFilename)
i = i + 1
print("Total files renamed: " + str(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment