Use shutil.move(src, dst) or pathlib.Path.rename(dst) (or Path.replace(dst) to overwrite an existing destination safely across platforms)—preferring shutil.move() whenever the source and destination might reside on different filesystems/drives or when you want to pass a destination directory directly without repeating the filename.
Basic Example
import shutil
from pathlib import Path
source = Path("reports/draft.pdf")
dest_dir = Path("archive/2026")
# Ensure destination directory exists
dest_dir.mkdir(parents=True, exist_ok=True)
# 1. Recommended (cross-filesystem safe, accepts directory OR full file path):
moved_path = shutil.move(source, dest_dir)
print(moved_path) # Output: "archive/2026/draft.pdf"
# 2. Pure pathlib alternative (same filesystem; must include the target filename):
# Path("reports/draft.pdf").replace(dest_dir / "draft.pdf")
Key Details & Edge Cases
- Passing a directory path vs. full file path (
shutil.movevs.Path.rename):shutil.move("a/file.txt", "b/")automatically movesfile.txtinto directoryb/asb/file.txt. However, if"b"does not exist yet (and has no trailing slash),shutil.move("a/file.txt", "b")renamesfile.txtto a file namedb—so always calldest_dir.mkdir(parents=True, exist_ok=True)first.Path.rename()andPath.replace()require the full destination file path (Path("a/file.txt").replace(Path("b/file.txt"))); passing just the directoryPath("b")raisesIsADirectoryError(on Linux/macOS) orFileExistsError(on Windows).
- Overwriting existing destination files across OSes (
FileExistsErroron Windows):- On Windows,
Path.rename(target)(andos.rename()) raisesFileExistsErroriftargetalready exists, whereas on Linux/macOS it overwrites atomically. UsePath.replace(target)(oros.replace()) for consistent cross-platform overwriting, or pass the full target file pathshutil.move(src, dest_dir / src.name)soshutil.moveoverwrites rather than nesting inside an existing directory.
- On Windows,
- Moving across drives or partitions (
OSError: [Errno 18] Invalid cross-device link):Path.rename(),Path.replace(), andos.rename()rely on an atomic filesystem metadata rename and fail withEXDEV(Invalid cross-device link) when moving between different drives (e.g.,C:\toD:\) or Docker bind-mount volumes.shutil.move()handles this automatically: it performs an instant atomicos.rename()when on the same filesystem, and transparently falls back to copying (copy2, preserving metadata) + deleting the source file when crossing filesystems.
- Moving multiple files matching a pattern (
Path.glob):from pathlib import Path import shutil dest = Path("processed_csvs") dest.mkdir(parents=True, exist_ok=True) for csv_file in Path("incoming").glob("*.csv"): shutil.move(csv_file, dest / csv_file.name) - Avoid moving an open file on Windows: On Windows, moving a file while an open file handle still holds it raises
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process. Always exit anywith open(...)block before moving the file.
Comparison of File-Moving Methods in Python
| Method | Accepts Directory Only as dst? |
Works Across Drives / Partitions? | Overwrites Existing Target on Windows? | Best Used When |
|---|---|---|---|---|
shutil.move(src, dst) |
Yes (dst can be dir or file path) |
Yes (renames if same FS, copies+deletes across FS) | Yes (when dst includes filename) |
General-purpose file or folder moves, cross-drive moves, and moving into a directory. |
Path.replace(dst) |
No (must include target filename) | No (OSError: EXDEV across drives) |
Yes (atomic on same FS) | Safely moving and overwriting a file on the same filesystem across all OSes. |
Path.rename(dst) |
No (must include target filename) | No (OSError: EXDEV across drives) |
No (raises FileExistsError on Windows) |
Same-filesystem moves where existing target files on Windows must not be overwritten. |
os.replace(src, dst) |
No (must include target filename) | No (OSError: EXDEV across drives) |
Yes (atomic on same FS) | Low-level string path operations avoiding Path object overhead. |
You must log in or register to comment.
