简体   繁体   中英

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!

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)    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM