`shutil` provides high-level operations for files and directory trees. Use it when a task calls for moving files, copying a tree, or removing a nonempty tree. section 12.5 section 12.6.2
Choose the operation to match the job:
- `shutil.copytree` recursively copies a directory and its subdirectories, preserving permission mode and access and modification times. section 12.5
- `shutil.rmtree` recursively removes a directory tree, including its files. By contrast, `os.rmdir` removes only empty directories; use `rmtree` with care. section 12.4
- `shutil.move` moves a file to another location. For a straightforward move, `os.rename` may do the job without another import. section 12.6.2
# txt_file_size_and_move.py
import os
import shutil
size = 0
os.makedirs('backup', exist_ok=True)
for root, dirs, files in os.walk(os.curdir):
for file in files:
file_path = os.path.join(root, file)
if (not os.path.islink(file_path)
and os.path.splitext(file)[1] == '.test'
and "backup" not in file_path):
size += os.path.getsize(file_path)
shutil.move(file_path, 'backup')
print(f"Total size of all .test files that are not symlinks: {size} bytes")
This script creates a `backup` directory, walks the current directory tree, totals the sizes of non-symlink `.test` files, and moves matching files with `shutil.move`. Its path check keeps already backed-up files out of the move. section 12.6.2
For directory traversal, pair `shutil` with `os.walk`; `shutil` also offers functions for copying individual files. Consult the standard-library documentation when you need details beyond these operations. section 12.5

