Shutil Module in Python

From this tutorial, you will be learning about Python Shutil module. It facilitates operations on files which makes it one of the essential modules to learn. Read on to know more.

Note: The syntax used in the below section is for Python 3. You may change it to use with a different version of Python.

Python Shutil Module

Must Read – 9 Ways to Copy a File in Python

What is Shutil module?

The shutil in Python is a module that offers several functions to deal with operations on files and their collections. It provides the ability to copy and removal of files.

In a way, it is similar to the OS Module; however, the OS Module does have functions dealing with collections of files.

How does the Python Shutil module work?

The syntax to use the shutil module is as follows:

import shutil
shutil.submodule_name(arguments)

Some examples of its functions are copytree(), make_archive(), which(), rmtree(), copy(), copy2(), copystat(), move(), etc.

In the next section, you will learn to use the few common functions frequently used in everyday Python programming.

Program Examples

which() to show the directory of an exe

Here is a simple program to demonstrate which() method.

import shutil

shutil.which("python")

shutil.which("python3")

shutil.which("ls")

The output will come as:

Python Shutil Module - Which Method

copystat() on a file

Check another program to use the copystat() function.

import shutil

shutil.copystat("file_path", "path_to_file_where_you_want_to_copy")

The output will come as:

Python Shutil Module - CopyStat1

CopyStat2

move() to move a file

Below is the program to use move() to relocate a file from one location to another.

import shutil

shutil.move("file_path", "path_to_where_you_want_to_move_file")

The output will come as:

Python Shutil Module - Move1

Move2

copy() to copy a file

Here is the program to copy a file from one location to another using copy().

import shutil

shutil.copy("file_path", "path_to_directory_where_you_want_to_copy_to")

The output will come as:

Python Shutil Module - Copy1

Copy2

rmtree() to delete files from dirs and subdirs

This function removes all the contents of a directory recursively.

import shutil

shutil.rmtree("dir_path")

The output will come as:

import shutil
targetdir = '/tmp/reports/';
# Clear a directory using rmtree()
try:
    shutil.rmtree(targetdir)
except:
    print("Operation failed!")

Best,

TechBeamers