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 Fletcher20 May 2024
Create a copy of files that go to the tmp directory
To review the content of files being generated in the /tmp directory on an Ubuntu server before Microsoft Defender removes them, you can use several approaches.  Following is the approach we took. Real-Time MonitoringYou can set up a script to monitor the /tmp directory and log the...