Skip to content

shutil

The Python shutil module provides a higher-level interface for file operations, including copying and removal. It builds upon the capabilities of the os module. It’s particularly useful for managing files and directories.

Here’s a quick example:

Language: Python
>>> import shutil
>>> shutil.copyfile("source.txt", "destination.txt")
'destination.txt'

Key Features

  • Copies files and directories
  • Moves files and directories
  • Removes files and directories
  • Archives and unarchives files
  • Discovers available disk space

Frequently Used Classes and Functions

Object Type Description
shutil.copyfile() Function Copies the contents of a file to another file
shutil.copytree() Function Recursively copies an entire directory tree
shutil.move() Function Moves a file or directory to another location
shutil.rmtree() Function Recursively deletes a directory tree
shutil.disk_usage() Function Returns disk usage statistics about the given path

Examples

Move a file to a new directory:

Language: Python
>>> shutil.move("example.txt", "/new/location/example.txt")
'/new/location/example.txt'

Remove a directory and all its contents:

Language: Python
>>> shutil.rmtree("directory")

Common Use Cases

  • Copying and moving files or directories
  • Removing directories and their contents
  • Creating archives of directories
  • Checking disk space before performing file operations

Real-World Example

Suppose you want to organize a project by moving all .txt files from a source directory to a target directory and then creating a ZIP archive of the target directory:

Language: Python
>>> import shutil, os
>>> source_dir = "source_directory"
>>> target_dir = "target_directory"
>>> os.makedirs(target_dir, exist_ok=True)

>>> for filename in os.listdir(source_dir):
...     if filename.endswith(".txt"):
...         shutil.move(os.path.join(source_dir, filename), target_dir)
...
'target_directory/notes.txt'
'target_directory/report.txt'

>>> shutil.make_archive("target_archive", "zip", target_dir)
'/home/user/target_archive.zip'

This example demonstrates how to organize files and create a backup archive using the shutil module.

How to Get a List of All Files in a Directory With Python

Tutorial

How to Get a List of All Files in a Directory With Python

In this tutorial, you'll be examining a couple of methods to get a list of files and folders in a directory with Python. You'll also use both methods to recursively list directory contents. Finally, you'll examine a situation that pits one method against the other.

intermediate stdlib

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Oct. 15, 2026