Last modified: Feb 06, 2026 By Alexander Williams

How to Move Files in Python: A Complete Guide

Moving files is a common task in programming.

You might need to organize downloads or process uploaded data.

Python makes this easy with its built-in modules.

This guide will show you how.

Why Move Files with Python?

Automation is the key reason.

Manually moving files is slow and error-prone.

A Python script can do it instantly and reliably.

It is perfect for organizing folders or building file-based applications.

You can schedule scripts to run automatically.

This saves you a lot of time.

Understanding File Paths

Before moving files, you must understand paths.

A path tells Python where a file is located.

There are two main types: absolute and relative.

An absolute path starts from the root of your drive.

For example, C:\Users\Name\file.txt on Windows.

A relative path starts from your current working directory.

For example, documents/report.pdf.

Always use clear paths to avoid errors.

The shutil.move() Method

The primary tool for moving files is shutil.move().

It comes from the shutil (shell utility) module.

This function can move files and entire directories.

It also handles renaming files in the process.

First, you need to import the module.


import shutil

# Define source and destination paths
source = "data/old_report.txt"
destination = "archive/old_report.txt"

# Move the file
shutil.move(source, destination)
print(f"Moved {source} to {destination}")

In this example, a file is moved from a 'data' folder to an 'archive' folder.

The shutil.move() function does the work.

If the destination folder does not exist, an error occurs.

You must ensure the target directory exists first.

Moving and Renaming Files

You can rename a file while moving it.

Just change the filename in the destination path.


import shutil

source = "downloads/temp_data.csv"
# New name and location
destination = "processed/final_report.csv"

shutil.move(source, destination)
print("File moved and renamed successfully.")

The file temp_data.csv is moved and renamed to final_report.csv.

This is a very efficient two-in-one operation.

The os.rename() Method

Another way to move files is with os.rename().

It comes from the os module.

This function is simpler but has a key limitation.

It only works if the source and destination are on the same filesystem or drive.

It is best for simple renames or moves within the same disk.


import os

source = "project_draft_v1.py"
destination = "project/project_final.py"

os.rename(source, destination)
print("File renamed and relocated using os.rename.")

Here, the file is moved into a 'project' subfolder and renamed.

For moving files between different drives, use shutil.move() instead.

Handling Errors and Exceptions

Things can go wrong when moving files.

The file might not exist. The destination might be full.

You should always use try-except blocks.

This prevents your program from crashing.

It also gives you helpful error messages.


import shutil
import os

source = "important_document.pdf"
destination = "backup/important_document.pdf"

try:
    # Check if source exists
    if os.path.exists(source):
        shutil.move(source, destination)
        print("File move successful.")
    else:
        print(f"Error: The file {source} was not found.")
except PermissionError:
    print("Error: You don't have permission to move this file.")
except shutil.Error as e:
    print(f"A shutil error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

This code safely attempts the move.

It checks if the file exists first.

It catches specific errors like permission issues.

This is a robust approach for real-world scripts.

Moving Files in Practice: A Script Example

Let's build a practical script.

This script moves all .log files from a 'logs' folder to an 'archive' folder.

It also adds a timestamp to their names.


import shutil
import os
from datetime import datetime

source_dir = "logs"
dest_dir = "archive/logs_archive"

# Create destination folder if it doesn't exist
os.makedirs(dest_dir, exist_ok=True)

# Get current timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M")

# Loop through files in the source directory
for filename in os.listdir(source_dir):
    if filename.endswith(".log"):
        source_path = os.path.join(source_dir, filename)
        # Create new filename with timestamp
        new_name = f"{filename[:-4]}_{timestamp}.log"
        dest_path = os.path.join(dest_dir, new_name)

        # Move the file
        shutil.move(source_path, dest_path)
        print(f"Archived: {filename} -> {new_name}")

print("All log files have been archived.")

Archived: app.log -> app_20231026_1430.log
Archived: error.log -> error_20231026_1430.log
All log files have been archived.

This script is useful for automatic log management.

It shows how to combine moving files with other operations.

You can learn more about executing such scripts by reading our guide on How to Run Python File in Terminal.

Key Differences: shutil.move vs os.rename

Knowing which function to use is important.

Use shutil.move() when: You need a reliable, high-level operation. It works across different filesystems. It can move directories.

Use os.rename() when: You are simply renaming a file or moving it on the same drive. You want a lightweight, low-level function.

For most tasks, shutil.move() is the recommended choice.

Conclusion

Moving files in Python is straightforward.

The shutil.move() function is your main tool.

Remember to handle errors and check file paths.

You can now automate file organization and build powerful scripts.

Start by moving a single file, then try more complex operations.

Practice is the best way to learn. Try creating a script to organize your downloads folder automatically.

For the next step, learn how to run your Python scripts from the terminal to fully automate your workflows.