FileExistsError error

Tweet


os.rename function of Python
FileExistsError: [WinError 183] Cannot create a file when that file already exists
When such error occurs.

For example,
os.rename('a.txt', 'b.txt')
The error occurs because b.txt exists.

#solution1
if os.path.isfile('b.txt'):
    os.remove('b.txt')
os.rename('a.txt', 'b.txt')

#solution2
if os.path.exists('b.txt'):
    os.remove('b.txt')
os.rename('a.txt', 'b.txt')

#solution3
shutil.move('a.txt', 'b.txt')


Back