Python – Move and replace if same file already exist in destination.

Posted: January 14, 2020 in Scripts

When trying to move files in python, if, for destination, only folder is specified, and if file already exist in destination, python will raise an error that file already exists.

import shutil
import os

source = "C:\Users\user\Downloads\python-2.7.17.msi"
destination = "C:\Users\user\Desktop"
shutil.move(source, destination)

raise Error, "Destination path '%s' already exists" % real_dst
shutil.Error: Destination path 'C:\Users\user\Desktop\python-2.7.17.msi' already exists

In order to overwrite file (if one already exists in destination), we need to specify full path for destination,not only destination folder name, for example C:\Users\user\Downloads\python-2.7.17.msi

import shutil
import os

source = "C:\Users\user\Downloads\python-2.7.17.msi"
destination = "C:\Users\user\Desktop"
filename = os.path.basename(source)
dest = os.path.join(destination,filename)
shutil.move(source, dest)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s