Python - Renaming all files in a directory using a loop

Viewed 21727

I have a folder with images that are currently named with timestamps. I want to rename all the images in the directory so they are named 'captured(x).jpg' where x is the image number in the directory.

I have been trying to implement different suggestions as advised on this website and other with no luck. Here is my code:

path = '/home/pi/images/'
i = 0
for filename in os.listdir(path):
  os.rename(filename, 'captured'+str(i)+'.jpg'
  i = i +1

I keep getting an error saying "No such file or directory" for the os.rename line.

4 Answers

This will work

import glob2
import os


def rename(f_path, new_name):
    filelist = glob2.glob(f_path + "*.ma")
    count = 0
    for file in filelist:
        print("File Count : ", count)
        filename = os.path.split(file)
        print(filename)
        new_filename = f_path + new_name + str(count + 1) + ".ma"
        os.rename(f_path+filename[1], new_filename)
        print(new_filename)
        count = count + 1

the function takes two arguments your filepath to rename the file and your new name to the file

Related