Saturday, 22 September 2012

How to rename Large number of files sequentially!

Recently, I had a task to rename about 3000 files so they can form a pattern.
Being in a non-computer science background, this seemed to me like a tedious thing to do.
However, with the help of my friend, I figured it out.
Before I start off, this post is intended for people who are new or know nothing about shell scripts.

One of the solutions to this is using python.I choose to do it using python because it is easier to understand and I could modify the script later to manipulate files.I am using ubuntu OS and all the steps are done in command line interface.

'os' is a module in python that provides a unified interface to a number of operating system functions.It has a list of functions that lets you access the file system.
os.listdir(path) is a function in this module that returns a list containing the names of the entries in the directory given by path.The list is in arbitrary order.It does not include special entries ' . ' and ' .. ' even if they are present in the directory.

Here are the steps:

Step 1 : Navigate to the directory where the files are present.Create a file in .py format and open 
              Here I have named the file as ''.

Step 2 : Type the following code :

                        import os #import the os module

                        path = '.';  #initialise the path with the current directory.
                        i = 1;
                        files = os.listdir(path);  
                        for file in files:
                          if file.startswith('cmd'):
                          os.rename(file, str(i) + ".png"); #to rename file
                          i = i + 1; 

            Indentation is important in python , so make sure you give tabs at the right place.Here, I       named the file in '.png' format and the naming was intended to be in this sequence : 1.png ,2.png,3.png ,etc .You can give any string you want.
str() is a function that converts integer to string.

Step 3 : Save the file and close it. Now run the file while in the directory where the folders are.
              If you are using the terminal then just execute the file using the following command :
                         $ python

             Here, the file has been named .Give the name of the file in which the code is

Check out other functions of os. Happy coding :P.Thanks to Karthik.B for teaching this :).

No comments:

Post a Comment