Updated on

Python Example Script for Renaming Files

Instructions:

You'll be prompted to:
  • enter a regex to search for:
  • enter a new base name:
Lets say you answered:
  • .*jpg
  • picnic
All jpg files in the directory you are in will be renamed picnic1.jpg, picnic2.jpg, etc.

Python Code

#!/usr/local/bin/python

# Python Rename File 1.0 
# Author: Douglas Palovick
# License: GPL http://www.gnu.org/licenses/gpl.txt

import re, os
rxin = raw_input('enter a regex to search for:\n')
foo = re.compile(rxin)
newname = raw_input('enter a new base name:\n')
a = 0
for fname in os.listdir(os.getcwd()):
    allowed_name = re.compile(rxin).match
    if allowed_name(fname):
        # newfname = string.lower(re.sub(foo,
                                   # '', fname))
        # b = (newname + str(a))
        a += 1
        c = os.path.splitext(fname)
        b = (newname + str(a) + c[1])
        os.rename(fname, b)