Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Shutil Module in Python
    python

    Shutil Module in Python

    March 29, 2023No Comments7 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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-



    1. 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 –



    1. import


      os



    2. import


      shutil



    3. # Creating a

      new


      folder in the current directory


    4. os.mkdir(

      ‘javatpoint’


      )



    5. # It will show the empty folder

    6. print(

      ‘Empty Folder:’


      , os.listdir(


      ‘javatpoint’


      ))



    7. # testcompare.py file will be copied in the javatpoint folder

    8. shutil.copy(

      ‘testcompare.py’


      ,


      ‘javatpoint’


      )



    9. # After coping the file folder shows the file

    10. 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



    1. import


      os



    2. import


      shutil



    3. # hello.txt file will be copied

    4. source = r

      ‘D:\Python Project\javatpoint\hello.txt’





    5. # In the newly created foloder

    6. destination = r

      ‘D:\Python Project\NewFile’





    7. # Storing the

      new


      path of hello.txt file


    8. dest = shutil.copy(source, destination)


    9. # Print the

      new


      path


    10. 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



    1. # importing shutil module



    2. import


      shutil



    3. # It is a source path

    4. source = r

      “D:\Python Project\NewFolder”





    5. # It is a destination path

    6. destination = r

      “D:\Python Project\NewFolder”






    7. try


      :


    8. shutil.copy(source, destination)

    9. print(

      “File copied successfully.”


      )



    10. # If the given source and path are same

    11. except shutil.SameFileError:

    12. print(

      “Source and destination represents the same file.”


      )



    13. # If there is no permission to write

    14. except PermissionError:

    15. print(

      “Permission denied.”


      )



    16. # For other errors

    17. except:

    18. 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:



    1. 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 –



    1. import


      os



    2. import


      shutil



    3. # hello.txt file will be copied

    4. source = r

      ‘D:\Python Project\javatpoint\hello.txt’





    5. metadata = os.stat(source)

    6. print(metadata)


    7. # In the newly created foloder

    8. destination = r

      ‘D:\Python Project\NewFile’




    9. # Storing the

      new


      path of hello.txt file



    10. dest1 = shutil.copy2(source, destination)

    11. metadata = os.stat(dest1)


    12. print(

      “After copying file”


      )


    13. print(metadata)


    14. # Print the

      new


      path


    15. 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:



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



    1. 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 –



    1. import


      shutil



    2. # hello.txt file will be copied

    3. source = r

      ‘D:\Python Project\javatpoint\hello.txt’





    4. # In the newly created foloder

    5. destination = r

      ‘D:\Python Project\NewFile\hi.txt’




    6. # Storing the

      new


      path of hello.txt file



    7. dest1 = shutil.copyfile(source, destination)


    8. # Print the

      new


      path


    9. 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:



    1. shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)



    1. 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 –



    1. # importing shutil module



    2. import


      shutil



    3. # It is source path

    4. src = r

      ‘D:\Python Project\javatpoint’





    5. # It is destination path

    6. dest = r

      ‘D:\Python Project\NewFolder’





    7. # Copy the content of

    8. # source to destination

    9. dest1 = shutil.copytree(src, dest)


    10. # Now we print path of newly

    11. # created file

    12. 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:



    1. 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 –



    1. import


      shutil



    2. import


      os



    3. # location

    4. location_dir = r

      “D:\Python Project\NewFile”





    5. # directory

    6. directory = r

      “D:\Python Project\javatpoint”





    7. # path

    8. path1 = os.path.join(location_dir, directory)


    9. # removing directory

    10. 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:



    1. 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 –



    1. # importing shutil module



    2. import


      shutil



    3. # search the file

    4. cmd =

      ‘python’





    5. # Using shutil.which() method

    6. locating = shutil.which(cmd)


    7. # Print result

    8. 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.

    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language Shutil Module in Python
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePlot With Pandas Python Data Visualization Basics
    Next Article Strings and Character Data in Python

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.