Python shutil Module Tutorial

Python shutil provides a lot of high-level functions for files, folders, and directories management. The shutil comes as a built-in Python module and there is no need for installation. The shutil can be used to copy, remove, move files, and folders.

copy() Method

The shutil module provides the copy() method in order to copy the source file into the destination file or directory. During the copy operation, the file permissions are preserved which means not changed. But the file creation and modification times are updated. The syntax of the copy() method is like below.

copy(SOURCE,DESTINATION,*,follow_symlink)
  • SOURCE is the source file that will be copied into the DESTINATION. This parameter is required.
  • DESTINATION is the newly created file by copying the SOURCE. This parameter is required.
  • follow_symlink can be set as true in order to copy the symbolic links. By default this parameter is false. This parameter is optional.

In the following example, we will copy the myfile.txt into the “/home/ismail/Downloads/” directory or path.

import shutil

shutil.copy("myfile.txt","/home/ismail/Downloads/")

rmtree() Method

Another useful method provided by the shutil in the rmtree() method which is used to remove directories. This method can not remove or delete a symbolic link into a directory. In the following example, we will remove the “/home/ismail/Downloads” directory or folder.

import shutil

shutil.rmtree("/home/ismail/Downloads")

move() Method

The move() method is used to move files or directories. The move() method is very simple where the source file or directory and destination file or directory is provided. In the following example, we will move the “/home/ismail/work” into the “/home/ismail/myword“.

import shutil

shutil.move("/home/ismail/work","/home/ismail/mywork")

disk_usage() Method

Another useful method provided by the shutil module is the disk_usage(). The disk_usage() method requires a single parameter which is the path we want to get its size.

import shutil

shutil.disk_usage("/home")

The output is like below.

usage(total=125757390848, used=12945469440, free=106379747328)

Leave a Comment