How to Move and Rename Files or Directories in Python: Using shutil.move

In scenarios like organizing files, rotating logs, or processing backups, you often need to move files or directories to a different location.

To do this in Python, using the move() function from the standard library shutil module is the most common and reliable method. This function handles not only simple movement but also file renaming, and it automatically manages moves between different drives.

This article explains how to move files and directories using shutil.move().

目次

Basic Usage of shutil.move()

Import the shutil module and call it in the format move(source, destination).

Syntax:

import shutil

shutil.move(src, dst)
  • src (Source): The path of the file or directory you want to move.
  • dst (Destination): The destination path (a directory name or a new filename).

Specific Usage Examples

1. Moving a File to Another Directory

This is the case where you move a file into an existing directory.

import shutil
import os

# Source file and destination directory
source_file = "downloads/report_2025.pdf"
destination_dir = "documents/reports/"

print(f"Before move: {source_file}")

# Move the file to the directory
# The result will be: documents/reports/report_2025.pdf
try:
    new_path = shutil.move(source_file, destination_dir)
    print(f"Move complete: {new_path}")
except FileNotFoundError:
    print("Error: Source file not found.")

Execution Result:

Before move: downloads/report_2025.pdf
Move complete: documents/reports/report_2025.pdf

If the dst is a directory, the file is saved inside it with the same name.

2. Moving and Renaming (Renaming)

If you want to change the filename while moving, specify the new file path (including the filename) in dst. If you change the name within the same directory, this effectively becomes a simple “rename” operation.

import shutil

# Old configuration file
old_config = "config_v1.json"

# New name for backup (can also move to a directory and rename at the same time)
new_config = "backup/config_v1_old.json"

# Execute move and rename
shutil.move(old_config, new_config)

print(f"Changed '{old_config}' to '{new_config}'.")

3. Moving an Entire Directory

shutil.move() works exactly the same way for directories as it does for files.

import shutil

# Entire project folder
project_dir = "temp_project"

# Archive folder
archive_dir = "archive"

# Move the directory
# Resulting structure: archive/temp_project
shutil.move(project_dir, archive_dir)

print(f"Moved directory '{project_dir}' to '{archive_dir}'.")

Difference from os.rename()

There is also a function called os.rename() for moving files, but shutil.move() is generally recommended for the following reason:

  • Moving Between Different File Systems: os.rename() may fail when trying to move files between different disks or partitions (e.g., from Drive C to Drive D). On the other hand, shutil.move() automatically handles this by “copying the file and then deleting the original” if a direct move is not possible. You can use it without worrying about the environment.

Note: Overwriting Behavior

The behavior when a file with the same name already exists at the destination depends on the OS.

  • Unix/Linux/macOS: It will usually overwrite the file silently.
  • Windows: It may cause an error if the dst file already exists.

If you want to ensure overwriting or prevent it, it is important to check beforehand using os.path.exists().

Summary

  • Use shutil.move(src, dst) to move files or directories.
  • If dst is a directory, the file is moved inside. If it is a file path, the file is moved and renamed.
  • It supports moving entire directories.
  • It is more powerful than os.rename() because it supports moving files between different drives.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次