[SOlVED] FileExistsError: [WinError 183] Cannot create a file when that file already exists

Free Python Code - Aug 11 '23 - - Dev Community

welcome everybody ๐Ÿ™‚๐Ÿ–

Today I am going to share with you how to handel FileExistsError

This problem occurs when you create a file or folder that already exists
In this example
I created a folder named test
The first time I run the code, there is no problem
But in the second case, the problem occurs because of the repetition of the same thing, which is to create the folder that already exists


import os
os.mkdir('test')

Enter fullscreen mode Exit fullscreen mode

Suppose you want to save a text file in the test folder
But the folder does not exist
So you will create it first
Then save the file
But the next time a FileExistsError problem will occur because you repeat the same step, which is creating the folder
To solve this problem you should use try
In this code I have solved the problem in a simple way


import os

def save_file():
    f = open('test/file.txt', 'w')
    f.write('this is test')

try:
    save_file()
except Exception as e:
    os.mkdir('test')
    save_file()

Enter fullscreen mode Exit fullscreen mode

Now we're done
Don't forget to like and follow ๐Ÿ™‚

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .