0
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.**

azro
  • 53,056
  • 7
  • 34
  • 70
Payne
  • 3
  • 2
  • According to [the documentation](https://docs.python.org/3/library/os.html#os.rename): "On Windows, if dst exists a FileExistsError is always raised." –  Mar 10 '22 at 20:19
  • Does this answer your question? [Force Overwrite in Os.Rename](https://stackoverflow.com/questions/8107352/force-overwrite-in-os-rename) – tbhaxor Mar 10 '22 at 20:20

2 Answers2

0

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

ArchAngelPwn
  • 2,891
  • 1
  • 4
  • 17
0

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)
tbhaxor
  • 1,659
  • 2
  • 13
  • 43