I have a Source File which I'm moving to an Archive directory using
shutil.move(srcfile, dstdir)
But when the same file already exists in the archive destination directory it throws an error saying can't move the file exists already. So I would like to overwrite the existing file. Is there a way to do that?
I had this same question. In case anyone else is looking for a solution, here's what I did.
According to the shutil documentation, there isn't a direct way to do this. However, there is an easy fix using os.remove()
. Assuming that you are in the source directory and you are moving the file 'srcfile' to 'dstdir':
import shutil, os
try:
os.remove(dstdir+'srcfile')
except OSError:
pass
else:
shutil.move(srcfile, dstdir)`
This tries to clear 'dstdir' of 'srcfile' before it moves the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With