1

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 Answers2

2

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)
Paul J
  • 799
  • 1
  • 6
  • 16
  • This works. It was a dumb mistake by me lol but another issue was when I would run the script after fixing the order of the parameters, it would delete some of the images. For example, if I had 16 images, after running the script, I would have the images renamed, but would only now have 8 images. But when I used your method, this issue was resolved, so thank you for that as well – LeGOATJames23 Sep 14 '21 at 23:54
1

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

Sylvester Kruin
  • 3,294
  • 5
  • 16
  • 39