How to resolve FileExistsError: [WinError 183] Cannot create a file when that file already exists?

Question:

This error has been asked multiple times in this forum and I tried possible solution but I could not resolve the issue. It does rename the file successfully but still annoying because it gives the same error message. Appreciate your input/help on this. Thank you very much.

Error:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: '~$Master.xlsx' -> 'Master.xlsx'

Code:

import os

os.chdir("C:/Path")
#if not os.chdir("C:/Path"): ----> tried this but same issue
for file in os.listdir():
    if file.endswith(".xlsx"):
        os.rename(file, "Master.xlsx")
Asked By: JMC

||

Answers:

You are trying to rename all excel file to the same name, that can not be done. instead try to rename files with some change in names like this.

for count, file in enumerate(os.listdir()):
    if file.endswith(".xlsx"):
        os.rename(file, f"Master{count}.xlsx")
Answered By: Rohit

It looks like you are trying to rename a file that has the same name as the file you are trying to rename it to. When you call os.rename(), it first tries to create a new file with the new name, but since a file with that name already exists, it raises a FileExistsError.

To avoid this error, you can check if a file with the new name already exists before trying to rename the file. If a file with the new name exists, you can rename the existing file to a different name, or delete it before renaming the file.

Here is an example of how you can do this:

import os

os.chdir("C:/Path")

for file in os.listdir():
    if file.endswith(".xlsx"):
        if os.path.exists("Master.xlsx"):
            os.rename("Master.xlsx", "Old_Master.xlsx")
        os.rename(file, "Master.xlsx")

Answered By: Pooja
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.