Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting a file that already exists in the directory during shutil.move operation

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?

like image 566
user1345260 Avatar asked Oct 02 '22 16:10

user1345260


1 Answers

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.

like image 193
thecircus Avatar answered Oct 07 '22 17:10

thecircus