liveBook · Manning

Shutil

As explained in The Quick Python Book, Fourth Edition

shutil is a Python standard-library module providing high-level operations on files and collections of files.

`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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains the principal tree operations and demonstrates a file move, but defers detailed API usage to standard-library documentation.
Examples
Demonstrates a backup script that totals non-symlink `.test` files and moves them with shutil.move.
What it assumes
Assumes familiarity with Python paths and directory traversal; does not teach shutil's full API from scratch.
What you can do after
Apply it via shutil.move, shutil.copytree, or shutil.rmtree to move files, copy directory trees, or remove nonempty trees.
How it connects
Connects shutil to os.walk for traversal, os.rmdir for empty-directory removal, and os.rename and pathlib as moving alternatives.

Also explained in

Compare how 2 books explain shutil →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.