Search code examples
pythonpython-3.xcountrename

HOW TO FIX!?!? = FileExistsError: [WinError 183] Cannot create a file when that file already exists


I have been working on changing the names of all the files in my folder to the have the same name and also a number count. I'm still fairly new to python & have been working on this code. After each debugging I get another error and now I'm stuck.

I have 372 files in this folder that I need to rename to "prcp_2016_###" counting numbers as 000 - 372.

Here is the code I have been working with so far...

for count, f in enumerate(os.listdir()):
f_name, f_ext = os.path.splitext(f)
f_name = "prcp_2016_" + str(count)

new_name = f'{f_name}{f_ext}'
os.rename(f, new_name)

The error message I keep getting is:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'prcp_2016_10.asc' -> 'prcp_2016_2.asc'

If anyone could be of any assistance me and my graduate school education will be forever grateful :)


Solution

  • Try this, it will check if the file already exists before renaming it.

    for count, f in enumerate(os.listdir()):
        f_name, f_ext = os.path.splitext(f)
        f_name = "prcp_2016_" + str(count)
    
        new_name = f'{f_name}{f_ext}'
        if not os.path.exists(new_name):
            os.rename(f, new_name)
    

    Edit: if you want to see the exception like @JustLearning suggests, you should actually print the exception name like so:

    for count, f in enumerate(os.listdir()):
        f_name, f_ext = os.path.splitext(f)
        f_name = "prcp_2016_" + str(count)
    
        new_name = f'{f_name}{f_ext}'
        try:
            os.rename(f, new_name)
        except Exception as e:
            print("Renaming didn't work because " + str(e))