Table of contents
1.
Introduction
2.
Shutil Module
3.
Copying Files 
4.
Copying Files along with their metadata
5.
Copying content of a file to another file
6.
Copying Directory
7.
Removing Directory
8.
Finding File
9.
Frequently Asked Questions
10.
Key Takeaways
Last Updated: Mar 27, 2024

Shutil Module in Python

Author APURV RATHORE
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Working with files in Python is one of the essential skills that one must know to master Python. One must know how to manipulate files such as copying, creating, or updating a file using code that will make it easy to automate the process. In this article, we will discuss this module.

Also read about, Divmod in Python, and Convert String to List Python

Shutil Module

The Shutil module allows you to do high-level operations on a file, such as copy, create, and remote operations. It falls within the umbrella of Python's basic utility modules. This module aids in the automation of the copying and deleting of files and folders. 

For working with the Shutil module, it must be imported first. The syntax for working with the Shutil module is as follows:

import shutil
shutil.submodule(args)
You can also try this code with Online Python Compiler
Run Code

 

Example of submodule are copy(), copy2(), copystat(), which(), copytree(), etc. 

See more, python ord

Copying Files 

Python's shutil.copy() function copies the content of a source file to a destination file or directory. The file's permission mode is kept, but other metadata, such as the file's creation and modification timings, is not.

The destination might be a file or a directory, but the source must be a file. If the destination is a directory, the file will be copied into the directory using the source's base filename. The final destination must also be writable. If the destination is a file, it will be replaced with the source file if it already exists; otherwise, a new file will be generated.

Syntax:

shutil.copy(src, dest, *, follow_symlinks = True)
You can also try this code with Online Python Compiler
Run Code

 

  • src: represents the source file path
  • dest: represents the path of the destination 
  • follow_symlinks: This is an optional parameter, and the default value of this parameter is True. If its value is False, and src is a symbolic link, the dest will be created as a symbolic link. 
This function returns the path of the newly created file. 
import os,shutil

print("The destination directory contents before",os.listdir('./Apurv/Work'))
src = './Apurv/A.txt'
dest = './Apurv/Work'

print(shutil.copy(src,dest))

print("The destination directory contents after",os.listdir('./Apurv/Work'))
You can also try this code with Online Python Compiler
Run Code

 

Output:

The destination directory contents before ['Hi']
./Apurv/Work\A.txt
The destination directory contents after ['A.txt', 'Hi']
PS D:\Course\Codeforces\New Codeforces> 
You can also try this code with Online Python Compiler
Run Code

Copying Files along with their metadata

Python's shutil.copy2() function copies the content of a source file to a destination file or directory. This function is similar to shutil.copy(), but it also tries to maintain the file's metadata.

Syntax:

shutil.copy2(src, dest, *, follow_symlinks = True)
You can also try this code with Online Python Compiler
Run Code
  • src: represents the source file path
  • dest: represents the path of the destination 
  • follow_symlinks: This is an optional parameter, and the default value of this parameter is True. If its value is False, and src is a symbolic link, then it tries to copy the metadata to the newly created dest symbolic link. 
     

This function returns the path of the newly created file. 

import os,shutil

print("The destination directory contents before",os.listdir('./Apurv/Work'))
src = './Apurv/A.txt'
dest = './Apurv/Work'

print("Meta data of the file before",os.stat(src))

final = shutil.copy2(src,dest)

print("Meta data of the file after",os.stat(final))
print("The destination directory contents after",os.listdir('./Apurv/Work'))
You can also try this code with Online Python Compiler
Run Code

 

Output:

The destination directory contents before ['Hi']Meta data of the file before os.stat_result(st_mode=33206, st_ino=844424930236549, st_dev=2956596288, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1644315867, st_mtime=1644315867, st_ctime=1644315867)
Meta data of the file after os.stat_result(st_mode=33206, st_ino=1125899906947206, st_dev=2956596288, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1644315867, st_mtime=1644315867, st_ctime=1644316661)
The destination directory contents after ['A.txt', 'Hi']
You can also try this code with Online Python Compiler
Run Code

 

In the above example, we can clearly see that the metadata is also copied along with the file using shutil.copy2() method.

You can compile it with online python compiler.

Copying content of a file to another file

In Python, the shutil.copyfile() function is used to copy the content of a source file to a destination file. The file's metadata is not copied. Both the source and the destination must be files, and the destination must be writable. If the destination file already exists, the source file will be overwritten; otherwise, a new file will be created.

If the source and destination files are identical, the SameFileError exception is thrown.

Syntax:

shutil.copyfile(src, dest, *, follow_symlinks = True)
You can also try this code with Online Python Compiler
Run Code
  • src: represents the source file path
  • dest: represents the path of the destination 
  • follow_symlinks: This is an optional parameter, and the default value of this parameter is True. If its value is False, and src is a symbolic link, then a new symbolic link will be generated instead of copying the file. 

This function returns the path of the newly created file. 

import os,shutil

src = './Apurv/A.txt'
dest = './Apurv/Work/B.txt'

final = shutil.copyfile(src,dest)
print("Destination: ",final)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Destination:  ./Apurv/Work/B.txt
You can also try this code with Online Python Compiler
Run Code

Copying Directory

The shutil.copytree() function copies a directory tree rooted at source (src) to the destination directory in a recursive manner. The destination target directory must not already exist. It will be produced as part of the copying process.

Syntax:

shutil.copytree(src, dest, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)
You can also try this code with Online Python Compiler
Run Code
  • src: represents the source file path
  • dest: represents the path of the destination 
  • symlinks: (optional) True or False, depending on whether the metadata of the original links or related links will be transferred to the new tree.
  • ignore (optional): If ignore is specified, it must be a callable that takes as arguments the directory that copytree() is visiting and a list of its contents, as produced by os.listdir ().
  • copy_function (optional): This parameter's default value is copy2. For this argument, we may also use other copy methods, such as the copy () method.
  • igonre_dangling_symlinks (optional): When this argument is set to True, the exception thrown if the file referenced by the symlink does not exist is silenced.

This function returns the path of the newly created file. 

import os,shutil

src = './Apurv/Hello'
dest = './Apurv/Work'
print("Before",os.listdir('./Apurv'))
path = shutil.copytree(src, dest)
print(path)
print("After",os.listdir('./Apurv'))
You can also try this code with Online Python Compiler
Run Code

 

Output:

Before ['A.txt', 'Hello']
./Apurv/Work
After ['A.txt', 'Hello', 'Work']
You can also try this code with Online Python Compiler
Run Code

Also read. python filename extensions

Removing Directory

The shutil.rmtree() function is used to delete an entire directory. The path must point to a directory but not a symbolic link to a directory. 

Syntax:

Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
You can also try this code with Online Python Compiler
Run Code
  • path: Represents the path of directory
  • ignore_errors: Errors arising from failed deletions will be ignored if ignore_errors is true.
  • oneerror: Errors are handled by invoking a handler defined by onerror if ignore_errors is false or omitted.
import os,shutil

src = './Apurv/Hello'

print("The contents before")
print(os.listdir("./Apurv"))
print()
shutil.rmtree(src)

print("The contents after")
print(os.listdir("./Apurv"))
You can also try this code with Online Python Compiler
Run Code

 

Output:

The contents before
['A.txt', 'Hello', 'Work']

The contents after
['A.txt', 'Work']
You can also try this code with Online Python Compiler
Run Code

 

Must Read Python List Operations

Finding File

The shutil.which() function returns the path to an executable program that will be executed if the specified cmd is executed. This approach may be used to locate a file on a machine that has been added to the PATH.

Syntax:

Syntax: shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)
You can also try this code with Online Python Compiler
Run Code
  • cmd: This argument is a string that represents the file
  • ignore_errors: This option determines the method's execution mode. os.F OK checks for the path's existence, whereas os.X OK checks for the path's existence. Checks if the path can be run, or in other words, mode checks whether the file exists and is executable.
  • path: This option defines the path to be utilised; if none is given, the results of os.environ() are used instead.

This function returns the path to the executable. 

import os,shutil

src = 'gradle'

path = shutil.which(src)

print(path)
You can also try this code with Online Python Compiler
Run Code

 

Output:

D:\program_files\gradle-7.3.3\bin\gradle.BAT
You can also try this code with Online Python Compiler
Run Code

 

Read more, Fibonacci Series in Python

Check out Escape Sequence in Python

Frequently Asked Questions

  1. What is Shutil Module in Python?
    Shutil module provides a range of high-level operations on files and file sets. There are methods that assist file copying and removal in particular.
     
  2. What are different operations supported by the Shutil?
    Different high-level operations on files and directories, such as copying files, copying directory, deleting directory, etc., are supported by the Shutil module. 
     
  3. What is the difference between the copy() and copy2() function in Shutil?
    Both the copy() and copy2() functions are used to copy files. But the copy() function does not copy the metadata such as date of creation, date of updation, etc., while copy2() copies the files along with its metadata. 

Key Takeaways

Congratulations on making it this far.

In this blog, we understood about Shutil module and its methods in Python.  

If you want to become proficient with Python programming, I suggest you take the Coding Ninjas Python Course, which will teach Python basics with Data Structures and Algorithms. 

Live masterclass