How to move a file in Python?
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:
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)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:
# 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.