Bulk Renaming Python Script

During a map reduce job, i was in need of bulk renaming input files to a specific pattern. Hence, wrote the below simple python script that can just do the job.

import os
import sys

run_ok = False
if len(sys.argv) == 5:
    directory_name = sys.argv[1]
    old_extension = sys.argv[2]
    name_pattern  = sys.argv[3]
    new_extension = sys.argv[4]
    print "Running jobs on directory: {} having extensions {}".format(directory_name, old_extension)
    run_ok = True

    print "SYNTAX : python file_rename.py directory_name matching_extension new_name_pattern new_extension"

if (run_ok):
    list = os.listdir( directory_name )
    counter = 1
    for old_file in list:
        if old_extension in old_file:
            new_file = name_pattern + str( counter ) + "." + new_extension
            os.rename( directory_name + "/"+ old_file, directory_name + "/" + new_file )
            print "file renamed from {} to {}".format( old_file, new_file )
            counter += 1

ট্যাগসমূহ:, , , ,

মন্তব্য করুন

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 /  পরিবর্তন )

Google+ photo

You are commenting using your Google+ account. Log Out /  পরিবর্তন )

Twitter picture

You are commenting using your Twitter account. Log Out /  পরিবর্তন )

Facebook photo

You are commenting using your Facebook account. Log Out /  পরিবর্তন )


Connecting to %s

%d bloggers like this: