Veejay
Veejay

Reputation: 417

Python - Renaming all files in a directory using a loop

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.

Upvotes: 8

Views: 28444

Answers (4)

murthy annavajhula
murthy annavajhula

Reputation: 11

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

Upvotes: 1

Will
Will

Reputation: 369

The results returned from os.listdir() does not include the path.

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

Upvotes: 16

cbo
cbo

Reputation: 96

Two suggestions:

  • Use glob. This gives you more fine grained control over filenames and dirs to iterate over.
  • Use enumerate instead of manual counting the iterations

Example:

import glob
import os

path = '/home/pi/images/'
for i, filename in enumerate(glob.glob(path + '*.jpg')):
    os.rename(filename, os.path.join(path, 'captured' + str(i) + '.jpg'))

Upvotes: 1

Anonta
Anonta

Reputation: 2540

The method rename() takes absolute paths, You are giving it only the file names thus it can't locate the files.

Add the folder's directory in front of the filename to get the absolute path

path = 'G:/ftest'

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

Upvotes: 1

Related Questions