Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to move list of folders with subfolders using Python?
Moving folders with their subfolders is a common task in file management and data organization. Python provides several built-in modules like shutil and os that make this process straightforward and reliable.
In this article, we will explore different approaches to move a list of folders with subfolders using Python, examining their syntax, use cases, and practical examples.
Why Python for Moving Folders?
Python's os and shutil modules provide powerful file system operations ?
- os module Low-level operating system interface for file operations
- shutil module High-level file operations with built-in error handling
- Cross-platform Works on Windows, macOS, and Linux
Method 1: Using shutil.move()
The shutil.move() function provides the simplest way to move folders with all their contents ?
Syntax
import shutil shutil.move(source, destination)
Example
import shutil
import os
# Create sample directory structure for demonstration
os.makedirs('source_folder/subfolder1/nested', exist_ok=True)
os.makedirs('source_folder/subfolder2', exist_ok=True)
os.makedirs('destination_folder', exist_ok=True)
# Create some sample files
with open('source_folder/subfolder1/file1.txt', 'w') as f:
f.write('Sample content')
with open('source_folder/subfolder1/nested/file2.txt', 'w') as f:
f.write('Nested content')
# Get list of subdirectories
source_folder = 'source_folder'
destination_folder = 'destination_folder'
subdirs = [os.path.join(source_folder, item)
for item in os.listdir(source_folder)
if os.path.isdir(os.path.join(source_folder, item))]
print("Moving folders:", subdirs)
# Move each subdirectory
for subdir in subdirs:
shutil.move(subdir, destination_folder)
print(f"Moved {subdir} to {destination_folder}")
print("Move operation completed!")
Moving folders: ['source_folder/subfolder1', 'source_folder/subfolder2'] Moved source_folder/subfolder1 to destination_folder Moved source_folder/subfolder2 to destination_folder Move operation completed!
Method 2: Using os.rename()
The os.rename() function works at a lower level and requires explicit path construction ?
Syntax
import os os.rename(source_path, destination_path)
Example
import os
# Create sample structure
os.makedirs('source2/folder_a/sub1', exist_ok=True)
os.makedirs('source2/folder_b', exist_ok=True)
os.makedirs('dest2', exist_ok=True)
source_folder = 'source2'
destination_folder = 'dest2'
# Get subdirectories
subdirs = [os.path.join(source_folder, item)
for item in os.listdir(source_folder)
if os.path.isdir(os.path.join(source_folder, item))]
print("Folders to move:", subdirs)
# Move using os.rename
for subdir in subdirs:
folder_name = os.path.basename(subdir)
new_path = os.path.join(destination_folder, folder_name)
os.rename(subdir, new_path)
print(f"Renamed {subdir} to {new_path}")
print("Rename operation completed!")
Folders to move: ['source2/folder_a', 'source2/folder_b'] Renamed source2/folder_a to dest2/folder_a Renamed source2/folder_b to dest2/folder_b Rename operation completed!
Method 3: Using shutil.copytree() and shutil.rmtree()
This approach first copies the directory tree, then removes the original ?
Syntax
import shutil shutil.copytree(source, destination) # Copy shutil.rmtree(source) # Remove original
Example
import shutil
import os
# Create sample structure
os.makedirs('source3/project_a/docs', exist_ok=True)
os.makedirs('source3/project_b/src', exist_ok=True)
os.makedirs('dest3', exist_ok=True)
# Add sample files
with open('source3/project_a/docs/readme.txt', 'w') as f:
f.write('Project documentation')
source_folder = 'source3'
destination_folder = 'dest3'
# Get subdirectories
subdirs = [os.path.join(source_folder, item)
for item in os.listdir(source_folder)
if os.path.isdir(os.path.join(source_folder, item))]
print("Copying and removing:", subdirs)
# Copy then remove (equivalent to move)
for subdir in subdirs:
folder_name = os.path.basename(subdir)
new_path = os.path.join(destination_folder, folder_name)
# Copy the entire directory tree
shutil.copytree(subdir, new_path)
print(f"Copied {subdir} to {new_path}")
# Remove the original
shutil.rmtree(subdir)
print(f"Removed original {subdir}")
print("Copy-remove operation completed!")
Copying and removing: ['source3/project_a', 'source3/project_b'] Copied source3/project_a to dest3/project_a Removed original source3/project_a Copied source3/project_b to dest3/project_b Removed original source3/project_b Copy-remove operation completed!
Comparison
| Method | Atomic Operation | Cross-filesystem | Error Handling | Best For |
|---|---|---|---|---|
shutil.move() |
Yes | Yes | Built-in | General purpose |
os.rename() |
Yes | No | Manual | Same filesystem |
copytree() + rmtree() |
No | Yes | More control | Complex scenarios |
Error Handling Example
import shutil
import os
def move_folders_safely(source_dir, dest_dir):
"""Safely move folders with error handling."""
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
try:
subdirs = [os.path.join(source_dir, item)
for item in os.listdir(source_dir)
if os.path.isdir(os.path.join(source_dir, item))]
for subdir in subdirs:
try:
shutil.move(subdir, dest_dir)
print(f"? Successfully moved {os.path.basename(subdir)}")
except Exception as e:
print(f"? Failed to move {os.path.basename(subdir)}: {e}")
except FileNotFoundError:
print(f"Source directory '{source_dir}' not found")
except PermissionError:
print("Permission denied - check file permissions")
# Example usage
move_folders_safely('nonexistent_source', 'some_dest')
Source directory 'nonexistent_source' not found
Conclusion
Use shutil.move() for most folder moving tasks as it handles cross-filesystem operations and provides built-in error handling. Use os.rename() for simple same-filesystem moves, and the copy-remove approach when you need more control over the process.
