To move a file or directory in Python, you can use the shutil.move()
function from the shutil
module. This method handles both file and directory relocation, works across different filesystems, and allows renaming during the move. Below are detailed examples and explanations:
1. Basic File Move
Move a file from one directory to another:
import shutil
# Define source and destination paths
source = "path/to/source/file.txt"
destination = "path/to/destination/folder/"
# Move the file (preserves filename)
shutil.move(source, destination)
Result:file.txt
is moved to destination/folder/
.
2. Move and Rename a File
Change the filename during the move:
import shutil
source = "data/old_name.csv"
destination = "archive/new_name.csv" # New name specified
shutil.move(source, destination)
Result:
File is moved to archive/
and renamed to new_name.csv
.
3. Move a Directory
Move an entire directory (including subdirectories and files):
import shutil
source_dir = "project/logs/"
destination_dir = "backup/old_logs/"
shutil.move(source_dir, destination_dir)
Result:
The logs/
directory is moved to backup/old_logs/
.
4. Error Handling
Gracefully handle missing files or permissions:
import shutil
source = "missing_file.txt"
destination = "destination/"
try:
shutil.move(source, destination)
except FileNotFoundError:
print(f"Error: {source} does not exist.")
except PermissionError:
print("Permission denied for the operation.")
5. Move Multiple Files
Use a loop to move all .txt
files from one directory to another:
import os
import shutil
source_folder = "source/"
destination_folder = "destination/"
# Create destination if it doesn't exist
os.makedirs(destination_folder, exist_ok=True)
# Move all .txt files
for file in os.listdir(source_folder):
if file.endswith(".txt"):
src = os.path.join(source_folder, file)
dest = os.path.join(destination_folder, file)
shutil.move(src, dest)
6. Move Files Across Filesystems
shutil.move()
automatically handles cross-device moves by copying and then deleting the source:
import shutil
# Source and destination on different drives
source = "/mnt/usb/file.doc"
destination = "/home/user/documents/"
shutil.move(source, destination) # Works seamlessly
7. Overwrite Existing Files
By default, shutil.move()
overwrites existing files in the destination. To avoid this, check first:
import os
import shutil
source = "report.pdf"
destination = "reports/report.pdf"
if not os.path.exists(destination):
shutil.move(source, destination)
else:
print(f"{destination} already exists. Skipping move.")
8. Preserve Metadata
Metadata (e.g., timestamps) is preserved when moving within the same filesystem. For cross-device moves, shutil.copy2()
is used internally to retain metadata:
import shutil
source = "image.jpg"
destination = "photos/image.jpg"
shutil.move(source, destination) # Metadata preserved
Key Notes
- Cross-Platform Compatibility:
shutil.move()
works on Windows, macOS, and Linux. - Symbolic Links: Moves the link itself, not the target (use
shutil.copy()
to follow links). - Performance: In-place moves (same filesystem) are faster than cross-device moves (copy + delete).
Summary of Methods
Method | Use Case |
---|---|
shutil.move(src, dst) | General-purpose file/directory relocation. |
os.rename(src, dst) | Rename/move within the same filesystem (no cross-device support). |
By using shutil.move()
, you ensure robust file and directory movement in Python across diverse scenarios.