Skip to main content

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:

  1. Import the shutil module.
  2. Specify the source file's path (source_file) and the destination directory (destination_directory) where you want to move the file.
  3. Use os.path.join to combine the destination directory with the source file's base name to create the new file path.
  4. 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}")

 

Related articles

Andrew Fletcher06 May 2024
Exploring historical memory usage monitoring with Sysstat
In the realm of system administration and monitoring, understanding memory usage trends is crucial for maintaining system health and performance. While tools like htop offer real-time insights into memory usage, they lack the capability to provide historical data. So, what if you need to analyze...