sajid khan sajid khan - 8 months ago 40
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]

for filename in filenames:
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!


Have you tried something like:

import os
filepath = 'C:/images/'
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)