W3docs

How to move a file in Python?

In Python, you can use the shutil module to move a file.

In Python, you can use the shutil module to move a file. The shutil module provides several functions for working with files and directories, including the move() function, which can be used to move a file from one location to another.

Here's an example of how you can use the shutil.move() function to move a file:

Use the shutil.move() function to move a file in Python

import shutil

# The path to the file you want to move
file_path = '/path/to/file.txt'

# The destination path for the file
destination_path = '/path/to/destination/'

# Move the file
shutil.move(file_path, destination_path)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

In this example, file_path is the path to the file you want to move, and destination_path is the path to the directory where you want to move the file. When you call the shutil.move() function, it will move the file at file_path to the directory specified by destination_path. If in the destination already exist a file with the same name , it will replace that with the file you want to move.

It's also possible to move a file and also rename it at the same time:

Move a file and also rename it at the same time in Python

# The path to the file you want to move
file_path = '/path/to/file.txt'

# The destination path for the file, with new name
destination_path = '/path/to/destination/file_new_name.txt'

# Move the file
shutil.move(file_path, destination_path)

It will move the file.txt to the destination directory and also rename it to file_new_name.txt

Keep in mind that, this method will also work for directories, not only for files.