sajid khan sajid khan - 1 month ago 7
Python Question

rename all file in a directory using Python

I want to Make a Python program that takes a folder name from the input argument, and then renames all its files by adding an "_{n}" at the end of it where n is the serial of that file. For example, if folder "images" contained, "images/cat.jpg", "images/dog.jpg", then after running the command, it will have "images/cat_1.jpg", "images/dog_2.jpg" . Sort the files according to last accessed date. I tried the problem partially as following:-

import os
from os import rename
from os.path import basename

path = os.getcwd()
filenames =next(os.walk(path))[2]
countfiles=len(filenames)

for filename in filenames:
fname=os.path.splitext(filename)[0]
ext=os.path.splitext(filename)[1]
old=fname+ext
new=fname + '_' +ext
os.rename(old, new)


this can rename the file adding an under score at the end of file name.However, I have no idea to add serial of files after the underscore. I would like to know how to batch rename the files using a simple Python script. I would appreciate any advice.

Thank you!

Answer

Have you tried something like:

import os
filepath = 'C:/images/'
os.chdir(filepath)
for num, filename in enumerate(os.listdir(os.getcwd()), start= 1):
    fname, ext = filename, ''
    if '.' in filename:
        fname, ext = filename.split('.')
    os.rename(filename, fname + '_%s' %num + '.' + ext)    
Comments