Move and replace if same file name already exists?

user1891916 picture user1891916 · Aug 4, 2015 · Viewed 96.2k times · Source

Here is below code which will move and replace individual file:

import shutil
import os
src = 'scrFolder'
dst = './dstFolder/'
filelist = []

files = os.listdir( src )
for filename in files:
    filelist.append(filename)
    fullpath = src + '/' + filename
    shutil.move(fullpath, dst)

If I execute same command and moving file which already existed in dst folder, I am getting shutil.Error: Destination path './dstFolder/file.txt' already exists. How to do move and replace if same file name already exists?

Answer

ecatmur picture ecatmur · Aug 4, 2015

If you specify the full path to the destination (not just the directory) then shutil.move will overwrite any existing file:

shutil.move(os.path.join(src, filename), os.path.join(dst, filename))