This post will discuss how to move a file in Python.

1. Using os.rename() function

A simple solution to move a Python file is using the os.rename() function.

Download Code

2. Using os.replace() function

The os.rename() function raises an exception when destination file already exist. If you want to overwrite the destination file, use os.replace().

Download Code

3. Using shutil.move() function

Alternatively, you can use the shutil module, which offers several high-level operations on files. To move a file, shutil.move() function can be used.

Download Code

 
Note that os.rename() doesn’t work if the destination file is on a different file system. The shutil.move() calls os.rename() when the destination is on the current file system. Otherwise, it will copy the source file to the destination location and then delete the source file.

That’s all about moving a file in Python.