The Wayback Machine - https://web.archive.org/web/20241126214946/https://www.geeksforgeeks.org/shutil-module-in-python/
Open In App

Shutil Module in Python

Last Updated : 26 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Shutil module offers high-level operation on a file like a copy, create, and remote operation on the file. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. In this article, we will learn this module.

Copying Files to another directory

shutil.copy() method in Python is used to copy the content of the source file to the destination file or directory. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved.
The source must represent a file but the destination can be a file or a directory. If the destination is a directory then the file will be copied into the destination using the base filename from the source. Also, the destination must be writable. If the destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created.

Syntax: shutil.copy(source, destination, *, follow_symlinks = True)

Parameter:

  • source: A string representing the path of the source file.
  • destination: A string representing the path of the destination file or directory.
  • follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link.

Return Type: This method returns a string which represents the path of newly created file.

Example 1:

Python3




# Python program to explain shutil.copy() method
 
# importing shutil module
import shutil
 
source = "path/main.py"
destination ="path/main2.py"
 
# Copy the content of
# source to destination
dest = shutil.copy(source, destination)
 
# Print path of newly
# created file
print("Destination path:", dest)


Output:

Destination path: path/main2.py

Example 2: If the destination is a directory.

Python3




# importing shutil module 
import shutil
   
# Source path
source = "path/main.py"
   
# Destination path
destination = "path/gfg/"
   
# Copy the content of
# source to destination
dest = shutil.copy(source, destination)
   
 
# Print path of newly 
# created file
print("Destination path:", dest)


Output:

path/gfg/main.py

Copying the Metadata along with File

shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata.

Syntax: shutil.copy2(source, destination, *, follow_symlinks = True)

Parameter:

  • source: A string representing the path of the source file.
  • destination: A string representing the path of the destination file or directory.
  • follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then it attempts to copy all metadata from the source symbolic link to the newly-created destination symbolic link. This functionality is platform dependent.

Return Type: This method returns a string which represents the path of newly created file.

Python3




# Python program to explain shutil.copy2() method
     
# importing os module
import os
 
# importing shutil module
import shutil
 
# path
path = 'csv/'
 
# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))
 
 
# Source path
source = "csv/main.py"
 
# Print the metadeta
# of source file
metadata = os.stat(source)
print("Metadata:", metadata, "\n")
 
# Destination path
destination = "csv/gfg/check.txt"
 
# Copy the content of
# source to destination
dest = shutil.copy2(source, destination)
 
# List files and directories
# in "/home / User / Documents"
print("After copying file:")
print(os.listdir(path))
 
# Print the metadata
# of the destination file
matadata = os.stat(destination)
print("Metadata:", metadata)
 
# Print path of newly
# created file
print("Destination path:", dest)


Output:

Before copying file:

[‘archive (2)’, ‘c.jpg’, ‘c.PNG’, ‘Capture.PNG’, ‘cc.jpg’, ‘check.zip’, ‘cv.csv’, ‘d.png’, ‘Done! Terms And Conditions Generator – The Fastest Free Terms and Conditions Generator!.pdf’, ‘file1.csv’, ‘gfg’, ‘haarcascade_frontalface_alt2.xml’, ‘log_transformed.jpg’, ‘main.py’, ‘nba.csv’, ‘new_gfg.png’, ‘r.gif’, ‘Result -_ Terms and Conditions are Ready!.pdf’, ‘rockyou.txt’, ‘sample.txt’]

Metadata: os.stat_result(st_mode=33206, st_ino=2251799814202896, st_dev=1689971230, st_nlink=1, st_uid=0, st_gid=0, st_size=1916, st_atime=1612953710, st_mtime=1612613202, st_ctime=1612522940) 

After copying file:

[‘archive (2)’, ‘c.jpg’, ‘c.PNG’, ‘Capture.PNG’, ‘cc.jpg’, ‘check.zip’, ‘cv.csv’, ‘d.png’, ‘Done! Terms And Conditions Generator – The Fastest Free Terms and Conditions Generator!.pdf’, ‘file1.csv’, ‘gfg’, ‘haarcascade_frontalface_alt2.xml’, ‘log_transformed.jpg’, ‘main.py’, ‘nba.csv’, ‘new_gfg.png’, ‘r.gif’, ‘Result -_ Terms and Conditions are Ready!.pdf’, ‘rockyou.txt’, ‘sample.txt’]

Metadata: os.stat_result(st_mode=33206, st_ino=2251799814202896, st_dev=1689971230, st_nlink=1, st_uid=0, st_gid=0, st_size=1916, st_atime=1612953710, st_mtime=1612613202, st_ctime=1612522940)

Destination path: csv/gfg/check.txt

Example 2: If the destination is a directory

Python3




# Python program to explain shutil.copy2() method
# importing os module
import os
 
# importing shutil module
import shutil
 
# Source path
source = "csv/main.py"
 
# Destination path
destination = "csv/gfg/"
 
# Copy the content of
# source to destination
dest = shutil.copy2(source, destination)
 
# List files and directories
# in "/home / User / Desktop"
print("After copying file:")
print(os.listdir(destination))
 
# Print path of newly
# created file
print("Destination path:", dest)


Output:

After copying file:

[‘cc.jpg’, ‘check.txt’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’]

Destination path: csv/gfg/main.py

Copying the content of one file to another

shutil.copyfile() method in Python is used to copy the content of the source file to the destination file. The metadata of the file is not copied. Source and destination must represent a file and destination must be writable. If the destination already exists then it will be replaced with the source file otherwise a new file will be created.

If source and destination represent the same file then SameFileError exception will be raised.

Syntax: shutil.copyfile(source, destination, *, follow_symlinks = True)

Parameter:

  • source: A string representing the path of the source file.
  • destination: A string representing the path of the destination file.
  • follow_symlinks (optional) : The default value of this parameter is True. If False and source represents a symbolic link then a new symbolic link will be created instead of copying the file.

Return Type: This method returns a string which represents the path of newly created file.

Python3




# Python program to explain shutil.copyfile() method
# importing shutil module
import shutil
 
# Source path
source = "csv/main.py"
 
# Destination path
destination = "csv/gfg/main_2.py"
 
dest = shutil.copyfile(source, destination)
 
print("Destination path:", dest)


Output:

Destination path: csv/gfg/main_2.py

Replicating complete Directory

shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying.

Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, ignore_dangling_symlinks = False)

Parameters:
src: A string representing the path of the source directory.
dest: A string representing the path of the destination.
symlinks (optional) : This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.
ignore (optional) : If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().
copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy() for this parameter.
ignore_dangling_symlinks (optional) : This parameter value when set to True is used to put a silence on the exception raised if the file pointed by the symlink doesn’t exist.

Return Value: This method returns a string which represents the path of newly created directory.

Python3




# Python program to explain shutil.copytree() method
# importing os module
import os
 
# importing shutil module
import shutil
 
# path
path = 'C:/Users/ksaty/csv/gfg'
 
print("Before copying file:")
print(os.listdir(path))
 
# Source path
src = 'C:/Users/ksaty/csv/gfg'
 
# Destination path
dest = 'C:/Users/ksaty/csv/gfg/dest'
 
# Copy the content of
# source to destination
destination = shutil.copytree(src, dest)
 
print("After copying file:")
print(os.listdir(path))
 
# Print path of newly
# created file
print("Destination path:", destination)


Output:

Before copying file:

[‘cc.jpg’, ‘check.txt’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’, ‘main_2.py’]

After copying file:

[‘cc.jpg’, ‘check.txt’, ‘dest’, ‘log_transformed.jpg’, ‘main.py’, ‘main2.py’, ‘main_2.py’]

Destination path: C:/Users/ksaty/csv/gfg/dest

Removing a Directory

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

Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)

Parameters:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.

Python3




# Python program to demonstrate
# shutil.rmtree()
 
import shutil
import os
 
# location
location = "csv/gfg/"
 
# directory
dir = "dest"
 
# path
path = os.path.join(location, dir)
 
# removing directory
shutil.rmtree(path)


Finding files

shutil.which() method tells the path to an executable application that would be run if the given cmd was called. This method can be used to find a file on a computer which is present on the PATH.

Syntax: shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)
Parameters:
cmd: A string representing the file.
mode: This parameter specifies mode by which method should execute. os.F_OK tests existence of the path and os.X_OK Checks if path can be executed or we can say mode determines if the file exists and executable.
path: This parameter specifies the path to be used, if no path is specified then the results of os.environ() are used
Return Value: This method returns the path to an executable application

Python3




# importing shutil module 
import shutil 
   
# file search 
cmd = 'anaconda'
   
# Using shutil.which() method
locate = shutil.which(cmd)
   
# Print result
print(locate)


Output:

D:\Installation_bulk\Scripts\anaconda.EXE


Previous Article
Next Article

Similar Reads

Python | shutil.get_archive_formats() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_archive_formats() method in Python is used to get the list of supported formats for archivin
1 min read
Python | shutil.copy() method
C/C++ Code # Python program to explain shutil.copy() method # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied su
5 min read
Python | shutil.copy2() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copy2() method in Python is used to copy the content of source file to destination file or direct
4 min read
Python | shutil.get_unpack_formats() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_unpack_formats() method in Python is used to get the list of all supported formats available
2 min read
Python | shutil.disk_usage() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.disk_usage() method in Python is to get disk usage statistics about the given path. This method
2 min read
Python | shutil.unregister_unpack_format() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.unregister_unpack_format() method in Python is used to unregister or remove an unpack format fro
2 min read
Python | shutil.unregister_archive_format() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. shutil.unregister_archive_format() method in Python is used to unregister or remove an archive form
2 min read
Python | shutil.copystat() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copystat() method in Python is used to copy the permission bits, last access time, last modificat
3 min read
Python | shutil.copymode() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories.shutil.copymode() method in Python is used to copy the permission bits from the given source path to
2 min read
Python | shutil.disk_usage() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.disk_usage() method tells the disk usage statistics about the given path as a named tuple with t
2 min read
Python | shutil.copytree() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the dest
3 min read
Python | shutil.chown() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.chown() method in Python is used to change the owner and /or group of the specified path. Syntax
3 min read
Python | shutil.copyfileobj() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.copyfileobj() method in Python is used to copy the contents of a file-like object to another fil
2 min read
Delete an entire directory tree using Python | shutil.rmtree() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. shutil.rmtree() is used to delete an entire directory tree, path must point to a directory (but not
3 min read
Python | shutil.get_terminal_size() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_terminal_size() method tells the size of the terminal window. As terminal is of the two dime
1 min read
Difference Between os.rename and shutil.move in Python
When it comes to renaming or moving files and directories, two commonly used methods are os. rename and shutil. move. While both can serve the purpose of renaming and moving, they have distinct differences in terms of functionality and use cases. In this article, we will explore these differences and when to use each of them. Difference Between os.
3 min read
Python | shutil.copyfile() method
Shutil module in Python helps automate the process of copying and removing files and directories. It comes under Python’s standard utility modules. Shutil(short for shell utility) module also provides many functions of high-level operations on files and collections of files. What is Shutil.copyfile() method?The shutil.copyfile() method in Python is
4 min read
Python | shutil.which() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps to automate the process of copying and removal of files and directories. shutil.which() method tells the path to an executable application that would be run if the given cmd
2 min read
Python | shutil.unpack_archive() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.unpack_archive() method in Python is used to unpack an archive file. Syntax: shutil.unpack_archiv
2 min read
Python | shutil.move() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removing files and directories. The shutil.move() method moves a file or directory from a source to a destination. It handles directo
2 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg