Python - Move and replace if same file name already exists

By xngo on May 7, 2022

shutil.move() function will move file to directory but it doesn't overwrite existing file if you don't provide the destination parameter with the full path, including the filename. Here, I create move_file() function to resolve this issue:

# Create test-dir/ directory.
import pathlib
dirname = "test-dir"
# Create a original file.
import os
filename = "test-file.txt"
filepath = os.path.join(dirname, filename)
fstream = open(filepath, "w")
# Create a file.
fstream = open(filename, "a")
# Move file and overwrite it if it exists.
import os
import shutil
def move_file(filepath, dest):
    # Convert to absolute paths.
    filepath = os.path.abspath(filepath)
    dest     = os.path.abspath(dest)
    # If destination is a directory, use full path, including filename.
    if os.path.isdir(dest):
        filename = os.path.basename(filepath)
        dest_filepath = os.path.join(dest, filename)
        shutil.move(filepath, dest_filepath)
        shutil.move(filepath, dest)
move_file(filename, dirname)
# move_file(filename, os.path.join(dirname, filename))

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.