How to move all files from one directory to another in Python

Published on Aug. 22, 2023, 12:15 p.m.

To move all files from one directory to another in Python, you can use the shutil module. Here’s an example:

import os
import shutil

# Define source and target directories
source_dir = "/path/to/source/directory"
target_dir = "/path/to/target/directory"

# Get a list of all files and directories in the source directory
files = os.listdir(source_dir)

# Move each file to the target directory
for file_name in files:
    # Generate the full path for each file
    src_path = os.path.join(source_dir, file_name)
    trg_path = os.path.join(target_dir, file_name)
    # Use shutil.move() to move the file to the target directory
    shutil.move(src_path, trg_path)

In this example, we start by specifying the source and target directories. We then use os.listdir() to get a list of all files and directories in the source directory. Finally, we iterate over each file in the list and use shutil.move() to move the file to the target directory.

Note that this will only move files, not subdirectories. If you also want to move subdirectories, you will need to use a recursive function.

Also, it’s important to be careful when using the shutil.move() function, especially if you’re moving files between different drives, as it could potentially result in data loss or corruption. Make sure to test your code thoroughly before using it in production.

Tags:

os