Home > database >  Replacing Files names of images with list names
Replacing Files names of images with list names

Time:03-11

import os

folder = 'H:/dataset/train/'
for enum,file_name in enumerate(os.listdir(folder)):
    source = folder   file_name
    destination = folder   y[enum]
    os.rename(source, destination)
FileExistsError                          
Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_5280/52172921.py in <module>
      5     source = folder   file_name
      6     destination = folder   y[enum]
----> 7     os.rename(source, destination)
      8     os.unlink(source) FileExistsError: [WinError 183] Cannot create a file when that file already exists:  'H:/dataset/train/001d7af96b.jpg' -> 'H:/dataset/train/Badminton.jpg'

This is how destination and source look like

img

sorry for the bad explanation of the problem and English.**

CodePudding user response:

On checking the error message, You cannot rename the file that already exists. In this case 'H:/dataset/train/Badminton.jpg'. However, you can use os.replace method to do this forcefully.

Fix:

import os

folder = 'H:/dataset/train/'
for enum,file_name in enumerate(os.listdir(folder)):
    source = folder   file_name
    destination = folder   y[enum]
    os.replace(source, destination)

CodePudding user response:

I believe this is what you are trying to do:

import os

y = ['test.csv', 'test2.csv']

folder = r'H:/dataset/train/'
for enum,file_name in enumerate(os.listdir(folder)):
    source = os.path.join(folder, file_name)
    destination = rf'{folder}\{enum}_{y[enum]}'
    os.rename(source, destination)
    print(destination)

I had to put in my own file names for the y, but you should be able to replace them if you need to. If you want to dynamically get those files from a file path you can do the following:

y = [file_name for file_name in os.listdir(folder)]
y

This will give you all of the files, but will simply put the enum in front of them so you can do it dynamically even it if means you have a number in front of the file

  • Related