Examples for shutil.move

Moving a File to a Different Directory

This code uses the shutil module to move a file from a source location to a destination directory. It first specifies the paths to the source file and the destination directory. Then, it calls shutil.move() with these paths to perform the move operation.

Python3




import shutil
 
# Source file path
source_file = 'source_directory/source_file.txt'
 
# Destination directory path
destination_directory = 'destination_directory/'
 
# Move the file to the destination directory
shutil.move(source_file, destination_directory)
 
print(f"File '{source_file}' has been moved to '{destination_directory}'.")


Output:

Moving a file to different directory

Handling Overwriting with shutil.move

This code uses the shutil library in Python to move a file from a source directory to a destination directory, potentially overwriting a file with the same name in the destination directory.

Python3




import shutil
 
# Source file path
source_file = 'source_directory/file.txt'
 
# Destination directory path
destination_directory = 'destination_directory/'
 
# Destination file path (same name as the source)
destination_file = 'destination_directory/file.txt'
 
# Move the file to the destination directory (overwrites if exists)
shutil.move(source_file, destination_file)
 
print(f"File '{source_file}' has been moved to '{destination_file
                                        }' (overwriting if necessary).")


Output:

Handling Overwriting with shutil.move



Difference Between os.rename and shutil.move in Python

When it comes to renaming or moving files and directories, two commonly used methods are os. rename and shutil. move. While both can serve the purpose of renaming and moving, they have distinct differences in terms of functionality and use cases. In this article, we will explore these differences and when to use each of them.

Similar Reads

Difference Between os. rename and shutil. move in Python

Both os. rename and shutil. move are valuable tool in Python for renaming and moving files and directories. The choice between them depends on the complexity of your task and the specific requirements of your file manipulation operation....

Examples for os.rename

Renaming a File...

Examples for shutil.move

...