简体   繁体   中英

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.

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

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'))

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

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

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