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:

#!/usr/bin/python3
 
# Create test-dir/ directory.
import pathlib
dirname = "test-dir"
pathlib.Path(dirname).mkdir(exist_ok=True)
 
# Create a original file.
import os
filename = "test-file.txt"
filepath = os.path.join(dirname, filename)
fstream = open(filepath, "w")
fstream.write("original")
fstream.close()
 
# Create a file.
fstream = open(filename, "a")
fstream.write("hello")
fstream.close()
 
# 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)
    else:
        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 OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.