Wednesday, February 24, 2010

Python - Bulk rename a directory of files

 
# I found myself with the need to rename my video 
# collection.  For some reason I decided that using 
# spaces in a file name is lame....underscores should 
# always be used.  After two or three files of manually 
# renaming I decided that python could do all the 
# work for me. 
 
import os
import glob
 
# My video collection is all matroska files.  So 
# the extension of them all is *.mkv format. 
files_to_change = '*.mkv' 
 
# new and old versions of a space 
lame_space = ' ';
cool_space = '_';
 
# use glob to gather a list of matching files 
for f in glob.glob(files_to_change):
        f2 = f
        f2 = f2.replace(lame_space, cool_space)
        # add a little status for instant gratification 
        print 'renaming: ', f, ' -> ', f2
        os.rename(f, f2)
 
print 'All Done' 
 
 
## my output: 
# 
# renaming:  Me at home.mkv  ->  Me_at_home.mkv 
# renaming:  Max in kid pool.mkv  ->  Max_in_kid_pool.mkv 
# ........ < and so on > 
# All Done 
 
 

No comments:

Post a Comment