I wanted to sort a group of pics in one of my folders by a general name along with an incremental number. Even though I’m the “Solution is already available, so why not do that?” kinda type, this time, I decided to write my own script to do it.
import os import sys # checking whether path and filename are given. if len(sys.argv) != 3: print "Usage : python rename.py <path> <new_name.extension>" sys.exit() # splitting name and extension. name = sys.argv.split('.') if len(name) < 2: name.append('') else: name = ".%s" %name # to name starting from 1 to number_of_files. count = 1 # creating a new folder in which the renamed files will be stored. s = "%s/pic_folder" % sys.argv try: os.mkdir(s) except OSError: # if pic_folder is already present, use it. pass try: for x in os.walk(sys.argv): for y in x: # creating the rename pattern. s = "%spic_folder/%s%s%s" %(x, name, count, name) # getting the original path of the file to be renamed. z = os.path.join(x,y) # renaming. os.rename(z, s) # incrementing the count. count = count + 1 except OSError: pass
Basically, the code first checks whether three arguments are given in the command line. The first argument being the program itself, the second one being the path and the third one being the naming that you want to perform. If one of the argument is missing, the code won’t execute.
After that the code processes the naming that you have given. It prepares the variable ‘name’ based on whether you have specified the naming with an extension or not.
Then we create a folder called “pic_folder” in the specified path. However, if a folder with that name is already present, we will use that folder itself.
The walk() function in the os module is pretty cool. It gives the entire path of the files present in the path that we give to it in a 3-tuple. One is the path to the directory. The second one is the name of subdirectories and the third one is the filename.
We then create a string ‘s’ with the new name and path followed by creating the path of the files to be renamed. Then we simply rename the files and increment the counter.
Try it out and let me know what bugs you about it.
The source code can be found at https://github.com/harisibrahimkv/tests/blob/master/rename.py too.