Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 994
Veejay Avatar asked Aug 11 '17 05:08

Veejay


People also ask

How do I rename all files in a directory in Python?

To rename files in Python, use the rename() method of the os module. The parameters of the rename() method are the source address (old name) and the destination address (new name).

How do I batch rename all files in a folder?

Using File Explorer To batch rename files, just select all the files you want to rename, press F2 (alternatively, right-click and select rename), then enter the name you want on the first file. Press Enter to change the names for all other selected files.

How do I rename all files in a folder sequentially?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.


2 Answers

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
like image 139
Will Avatar answered Oct 24 '22 12:10

Will


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
like image 38
Anonta Avatar answered Oct 24 '22 11:10

Anonta