Powered by Python: Rename files

I have too many files that I want to unify the naming schemes, by replacing all spaces(" ") with periods(".") and capitalizing each part. e.g "this is a file.txt" -> "This.Is.A.File.txt"

Python comes to rescue with a breeze.

  1: from os import walk
  2: from os.path import join
  3: from os.path import basename
  4: from string import capwords
  5: import datetime
  6: import sys
  7: import os
  8: 
  9: def GoRename(path):
 10:     """ this function take a valid directory path as input
 11:     walk through all files and directories in the passed in path,
 12:     Raname the file by replacing all spaces with dots, and capitalize each word
 13:     path: path to a directory or file
 14:     Copyright @ Tomgee, 2007
 15:     """
 16: 
 17:     print sys.getdefaultencoding()
 18:     print sys.getfilesystemencoding()
 19:     logfile = path + r'\log.txt'
 20:     print "Going through %s to rename files, \nsubdirectory included..."%(path)
 21:     print "a log will be saved to %s"%logfile
 22:     f = open(logfile, 'a') # open a log file
 23:     sys.stdout = f # un-comment this line out if the output to a file is preferred
 24:     now = datetime.datetime.now()
 25:     print "\n***********************************************"
 26:     print "Timestamp: %s"%now.strftime("%y-%m-%d, %H:%M:%S")
 27: 
 28:     totalCount = 0
 29:     for root,dirs, files in walk(path):
 30:         for file in files:
 31:         if (file != os.path.basename(sys.argv[0])) and (file != "log.txt")and " " in file:
 32:             newfile = ".".join(capwords(file).split(" "))
 33:             os.rename(file, newfile)
 34:             print "File #%d: %s --> %s"%(totalCount,file, newfile)
 35:             totalCount += 1
 36:     print "Totally %d files/directories under %s have been searched"%(totalCount, path)
 37:     print r'********* The End *********'
 38: 
 39: def main():
 40:     argCurDir = os.getcwd()
 41:     GoRename(argCurDir)
 42: 
 43: if __name__ == '__main__': main()
 44: 
Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: