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

Time:10-05

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

CodePudding user response:

You can handle any exceptions as:

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:
        print("Renaming didn't work because _____. Moving on...")
        continue

where the blank space in the print statement should be something useful for you and your graduate school education :)

That said, it's best to deal with exceptions instead of letting them be. The code above is generic to skip renamings that didn't work, but you should try to understand why they didn't work. For instance, is it expected to get repeated names in the loop?

CodePudding user response:

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))
  • Related