Python: Renaming Files in Directory

Viewed 154

I have a dataset of thousands of images downloaded from Kaggle and am wanting to rename the files. The images are all .png images. The current names of the images are all similar to 'Screen Shot 2018-06-08 at 5.08.37 PM.png' and am wanting to just rename them all to simple numbers (ex: 0.png, 1.png, 2.png, ..., 1234.png).

I am using a smaller dataset to test out code and see there is a rename() function in the os module. I currently have:

for count, filename in enumerate(os.listdir(data_dir_path)):
  dst = str(count) + '.png'
  src = str(data_dir_path) + '/' + filename
  dst = str(data_dir_path) + '/' + dst
  os.rename(dst, src)

This worked, however before I ran the script I had around 16 images, and now after running this script, I now only have the first 8.

data_dir_path = '/content/drive/MyDrive/Fruits/train/Fresh Apples/'
2 Answers

You have src and dst the wrong way round in os.rename(dst, src).

It's also a good idea to use os.path.join() instead of manually concatenating the separator / (let Python take care of it for you, and it will work across *nix/Windows/Mac):

for count, filename in enumerate(os.listdir(data_dir_path)):
    src = os.path.join(data_dir_path, filename)
    dst = os.path.join(data_dir_path, f'{str(count)}.png')
    os.rename(src, dst)

In the function os.rename(), the the arguments' order is src, dst. But you pass the arguments in the opposite order: dst, src, so you're trying to take the new image name and rename it to the old image name. This is what your code would look like with the order of the arguments passed to os.rename() changed:

for count, filename in enumerate(os.listdir(data_dir_path)):
    dst = str(count) + '.png'
    src = str(data_dir_path) + '/' + filename
    dst = str(data_dir_path) + '/' + dst
    os.rename(src, dst)

If this doesn't work, try os.rename(src=src, dst=dst).

Related