Move and replace if same file name already exists?

Python 2.7Shutil

Python 2.7 Problem Overview


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?

Python 2.7 Solutions


Solution 1 - Python 2.7

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))

Solution 2 - Python 2.7

I got it to overwrite by providing a full path for both source and target in the move command... remember to add double slash for Windows paths.

# this is to change directories (type your own)
os.chdir("C:\REPORTS\DAILY_REPORTS")

# current dir  (to verify)
cwd = os.getcwd() 
src = cwd
dst = cwd + '\\XLS_BACKUP\\'

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

# nice and short.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1891916View Question on Stackoverflow
Solution 1 - Python 2.7ecatmurView Answer on Stackoverflow
Solution 2 - Python 2.7Andres MartinezView Answer on Stackoverflow