Python’s Shutil Object Module
In this guide, we will get familiar with the Shutil module that is available in Python. Using the Python script, we will examine how to carry out high-level file operations such as making a new copy file and archiving it, as well as copying the content of one file to another file. Let’s begin with the most fundamental aspects of Shutil’s background.
module.
Python Shutil Module
The Python shutil module makes it possible to carry out high-level file operations by providing the functionality. It is able to perform operations on the file object and provides us with the ability to copy as well as delete files. It takes care of the low-level semantics, such as creating and closing file objects, once all other tasks have been completed.
operations.
Working of Shutil Module
The Python utility module provides with a large number of pre-defined methods. In this section, we will discuss a few key approaches. In order to begin using this module, we will first need to import it into the version of Python that we are currently using.
file.
Copy Files
It is possible to copy data from one file to another by using the copy() method that is provided by this module. Both the source file and the destination file have to be readable for the operation to be successful. Let’s get a grasp on the following syntactic structure. Syntax-
-
shutil.copyfile(source, destination, *, follow_symlinks = True)
Parameter:
In the syntax shown above
–
- The first argument is source which shows the path of source file.
- The second argument is destination which shows the path of the destination file.
- The third argument is optional; the default value of this parameter is true.
- It returns a string which shows the path of newly created file.
Let’s look at the following scenario and try to grasp it. Example –
-
import
os
-
import
shutil
-
-
# Creating a
new
folder in the current directory
-
os.mkdir(
‘javatpoint’
)
-
-
# It will show the empty folder
-
print(
‘Empty Folder:’
, os.listdir(
‘javatpoint’
))
-
-
# testcompare.py file will be copied in the javatpoint folder
-
shutil.copy(
‘testcompare.py’
,
‘javatpoint’
)
-
-
# After coping the file folder shows the file
-
print(
‘File Copied Name:’
, os.listdir(
‘javatpoint’
))
Output:
Explanation for the value
Empty Folder: [] File Copied Name: ['testcompare.py']
A directory’s name may be sent as an input to the copy() method. Since the metadata is not duplicated in this scenario, the file that was copied will be treated as if it had just been created. This approach cloned the file completely, including all of its permissions. It is important to keep in mind that the source file will be used to replace the destination file in the event that the target file already exists.
Let’s look at another illustration, shall we? Exhibit 2: In the event that a destination is a directory
-
import
os
-
import
shutil
-
-
# hello.txt file will be copied
-
source = r
‘D:\Python Project\javatpoint\hello.txt’
-
-
# In the newly created foloder
-
destination = r
‘D:\Python Project\NewFile’
-
-
# Storing the
new
path of hello.txt file
-
dest = shutil.copy(source, destination)
-
-
# Print the
new
path
-
print(dest)
Output:
D:\Python Project\NewFile\hello.txt
As this is something that has already been discussed, the copy() method does not transfer the metadata. On the other hand, we shall duplicate the file together with its information by using the copy2() function, which is available to us. Handling of errors when using the copy approach is Example No. 3
-
# importing shutil module
-
import
shutil
-
-
# It is a source path
-
source = r
“D:\Python Project\NewFolder”
-
-
# It is a destination path
-
destination = r
“D:\Python Project\NewFolder”
-
-
try
:
-
shutil.copy(source, destination)
-
print(
“File copied successfully.”
)
-
-
# If the given source and path are same
-
except shutil.SameFileError:
-
print(
“Source and destination represents the same file.”
)
-
-
# If there is no permission to write
-
except PermissionError:
-
print(
“Permission denied.”
)
-
-
# For other errors
-
except:
-
print(
“Error occurred while copying file.”
)
Output:
Source and destination represents the same file.
The copy2() Function
This function is comparable to the copy() method in its functionality. It is similarly capable of copying the contents of one file to another, but the key distinction is that it can maintain the metadata of the original file. Let’s get a grasp on the following syntactic structure. Syntax:
-
shutil.copy2(source, destination, *, follow_symlinks = True)
Parameter:
In the syntax shown above
–
- The first argument is source which shows the path of source file.
- The second argument is destination which shows the path of the destination file.
- The third argument is optional; the default value of this parameter is true.
- It returns a string which shows the path of newly created file.
Let’s look at the following scenario and try to grasp it. Example –
-
import
os
-
import
shutil
-
-
# hello.txt file will be copied
-
source = r
‘D:\Python Project\javatpoint\hello.txt’
-
-
metadata = os.stat(source)
-
print(metadata)
-
-
# In the newly created foloder
-
destination = r
‘D:\Python Project\NewFile’
-
# Storing the
new
path of hello.txt file
-
-
dest1 = shutil.copy2(source, destination)
-
metadata = os.stat(dest1)
-
-
print(
“After copying file”
)
-
print(metadata)
-
-
# Print the
new
path
-
print(dest1)
Output:
os.stat_result(st_mode=33206, st_ino=562949953459285, st_dev=3029671014, st_nlink=1, st_uid=0, st_gid=0, st_size=17, st_atime=1622815671, st_mtime=1622705607, st_ctime=1622705607) After copying file os.stat_result(st_mode=33206, st_ino=562949953459287, st_dev=3029671014, st_nlink=1, st_uid=0, st_gid=0, st_size=17, st_atime=1622815748, st_mtime=1622705607, st_ctime=1622706243) D:\Python Project\NewFile\hello.txt
The shutil.copyfile() Function
With the exception of the metadata, the content of the source file is copied over to the destination file using this approach. Both the source and the destination must have a file, and the permission to write must be granted on the destination file. If there is already a file in the destination directory, then the new file will overwrite the old one and a new file will be created otherwise.
The following is an example of proper syntax. Syntax:
Parameters:
-
shutil.copyfile(source, destination, *, follow_symlinks = True)
-
shutil.copyfile(source, destination, *, follow_symlinks = True)
In the syntax shown above
–
- The first argument is source which shows the path of source file.
- The second argument is destination which shows the path of the destination file.
- The third argument is optional; the default value of this parameter is true.
- It returns a string which shows the path of newly created file.
Let’s look at the following scenario and try to grasp it. Example –
-
import
shutil
-
-
# hello.txt file will be copied
-
source = r
‘D:\Python Project\javatpoint\hello.txt’
-
-
# In the newly created foloder
-
destination = r
‘D:\Python Project\NewFile\hi.txt’
-
# Storing the
new
path of hello.txt file
-
-
dest1 = shutil.copyfile(source, destination)
-
-
# Print the
new
path
-
print(dest1)
Output:
D:\Python Project\NewFile\hi.txt
The shutil.copytree() Function
This approach is used in order to duplicate the directory in its entirety. It duplicates a full directory tree, with its root at the source, and places it in the directory you provide as the destination. It is essential that the directory of destination not already exist. The following is an example of proper syntax. Syntax:
Parameters:
-
shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)
-
shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)
As said before
syntax:
-
src –
It shows the path of the source directory. -
dest –
It shows the path of the destination directory. -
symlinks(optional) –
It takes the Boolean values – True and False. It depends on which the metadata of original links or links will be copied to the new tree. -
ignore(optional) –
By default it is None but If the ignore is passed, it must be a callable that receive as its arguments. The directory is visited by copytree(). -
copy_function(optional) –
The copy2 is default value of this parameter. The
copy()
function can be used as parameter. -
ignore_dangling_symlinks(optional) –
This parameter is used to raise the exception if the file pointed by symlink doesn’t exist. - It returns the string which represents the path of newly created directory.
Sample –
-
# importing shutil module
-
import
shutil
-
-
# It is source path
-
src = r
‘D:\Python Project\javatpoint’
-
-
# It is destination path
-
dest = r
‘D:\Python Project\NewFolder’
-
-
# Copy the content of
-
# source to destination
-
dest1 = shutil.copytree(src, dest)
-
-
# Now we print path of newly
-
# created file
-
print(
“Destination path:”
, dest1)
Output:
Destination path: D:\Python Project\NewFolder
The shutil.rmtree()
This technique is used to remove the whole directory tree from the system. The following is an example of proper syntax. Syntax:
-
shutil.rmtree(path, ignore_errors=False, onerror=None)
Parameter-
In the syntax shown above
–
-
path –
It represents the file path. A path-like object is either a string or bytes object. -
ignore_errors –
The removal will be ignored if this argument is True. -
onerror –
If
ignore_errors
is false, such errors are handled by calling a handler specified by onerror.
Let’s look at the following example to see how it works: Example –
-
import
shutil
-
import
os
-
-
# location
-
location_dir = r
“D:\Python Project\NewFile”
-
-
# directory
-
directory = r
“D:\Python Project\javatpoint”
-
-
# path
-
path1 = os.path.join(location_dir, directory)
-
-
# removing directory
-
shutil.rmtree(path1)
The code that is shown above will delete the supplied.
directory.
The shutil.which() Function
The method shutil.which() is used to get the path of an executable application in order to determine which programme would be run if the specified cmd were to be executed. It locates the file using the path that was provided. The following is an example of proper syntax. Syntax:
-
shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)
Parameters
In the syntax shown above
–
-
cmd –
It is string that represents the file. -
mode –
It specifies the mode of file in which method should executed. -
path –
This parameter specifies the path to be used. - This method returns the path to an executable application.
Let’s look at the following scenario and try to grasp it. Example –
-
# importing shutil module
-
import
shutil
-
-
# search the file
-
cmd =
‘python’
-
-
# Using shutil.which() method
-
locating = shutil.which(cmd)
-
-
# Print result
-
print(locating)
Output:
C:\Python\python.EXE
It will search the computer for the specified file and, if it is discovered, it will provide the path to that file; otherwise, it will return nothing.