Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Recursively rename all files in a directory
#!/usr/bin/env python
# encoding: utf-8
# Recursively rename all files in a directory with the following rules:
# - Convert letters to lower case
# - Convert whitespace to underscore
# Used to clean up filenaming of mp3s
# Tim van Werkoven, 20090426 <>
# This file is licensed under the Creative Commons Attribution-Share Alike
# license versions 3.0 or higher, see
Created by Tim on 2009-04-26.
Copyright (c) 2009 Tim van Werkhoven. All rights reserved.
import sys
import getopt
import os
import time
help_message = '''Usage: rename <dir>
-v, --verbose increase verbosity
-d, --dry dry run, don't do anything, just list
-h, --help show this help
SKIPFILES = ['.DS_Store']
SKIPDIRS = ['.svn']
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
verbose = False
dry = False
if argv is None:
argv = sys.argv
opts, args = getopt.getopt(argv[1:], "hvd", ["help", "verbose", "dry"])
except getopt.error, msg:
raise Usage(msg)
# Path to rename
path = args[0]
if (not isinstance(path, type('string'))): raise Usage("Not a directory")
# option processing
for option, value in opts:
print 'Parsing %s:%s' % (option, value)
if option in ["-v", "--verbose"]:
verbose = True
if option in ["-h", "--help"]:
raise Usage(help_message)
if option in ["-d", "--dry"]:
dry = True
except Usage, err:
print >> sys.stderr, os.path.basename(sys.argv[0]) + ": " + str(err.msg)
print >> sys.stderr, "\t for help use --help"
return 2
beg = time.time()
# Start renaming here
if (verbose): print "Starting renaming of '%s'." % (path)
for (root, dirs, files) in os.walk(path, topdown=False):
if (verbose): print "Parsing directory '%s' now." % (root)
# rename all files and dirs to lower-case, replace space by _
for _f in files:
newf = (_f.lower()).replace(' ', '_')
if ((newf != _f) and (_f not in SKIPFILES)):
if (verbose): print "Renaming file '%s' to '%s'." % (_f, newf)
if (not dry): os.rename(os.path.join(root,_f), os.path.join(root,newf))
if (verbose): print "Skipping file '%s'." % (_f)
for _d in dirs:
newd = (_d.lower()).replace(' ', '_')
if (newd != _d):
if (verbose): print "Renaming dir '%s' to '%s'." % (_d, newd)
if (not dry): os.rename(os.path.join(root,_d), os.path.join(root,newd))
if (verbose): print "Skipping dir '%s'." % (_d)
dur = time.time() - beg
if (verbose): print "Done in %.4g seconds." % (dur)
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.