Andrew Fletcher published: 19 October 2023 2 minutes read
You can move a file from one directory to another in Python using the shutil module. The shutil module provides functions to perform various file operations, including moving files. How you can move a file from one directory to another:
import shutil
# Source file path (the file you want to move)
source_file = "/path/to/source_directory/file.txt"
# Destination directory (the directory where you want to move the file)
destination_directory = "/path/to/destination_directory/"
# Combine the destination directory with the source file name to get the new file path
new_file_path = os.path.join(destination_directory, os.path.basename(source_file))
# Move the file to the destination directory
shutil.move(source_file, new_file_path)
print(f"File has been moved to {new_file_path}")
In this code:
- Import the shutil module.
- Specify the source file's path (source_file) and the destination directory (destination_directory) where you want to move the file.
- Use os.path.join to combine the destination directory with the source file's base name to create the new file path.
- Use shutil.move to move the file from the source location to the destination directory.
After running this code, the file specified in source_file will be moved to the destination_directory with its original name. You can adjust the source and destination paths to match your specific file and directory locations.
In action
def relocatefile(file_name):
# Source file path (the file you want to move)
source_file = "./documents/%s" % (file_name)
# Destination directory (the directory where you want to move the file)
destination_directory = "./summarised"
# Combine the destination directory with the source file name to get the new file path
new_file_path = os.path.join(destination_directory, os.path.basename(source_file))
# Move the file to the destination directory
shutil.move(source_file, new_file_path)
print(f"File has been moved to {new_file_path}")