shutil
  • The shutil module includes high-level file operations such as copying and archiving
  • Copy Files
    import shutil
    
    # copyfile
    # copy the content of the source file to the destination file
    # the metadata of the file is not copied
    shutil.copyfile('shutil_copyfile.py', 'shutil_copyfile.py.copy')
    
    # copy
    # copy the content of source file to destination file or directory
    shutil.copy('p1.py', 'p2')
    
    # copy2
    # copy the content of source file to destination file or directory
    # preserves the file’s metadata
    shutil.copy2('p1.py', 'p2/p3.py')
    		
    Copy File Metadata
    # copymode
    # copy the permissions from one file to another
    shutil.copyfile('p1.py', 'p1_copy.py')
    shutil.copymode('p1.py', 'p1_copy.py')
    
    # copystat
    # copy the permissions and dates associated with the file
    shutil.copyfile('p1.py', 'p2_copy.py')
    shutil.copystat('p1.py', 'p2_copy.py')
            
    Directory
    # copytree
    # copy a directory from one place to another
    shutil.copytree('p2', 'p3')
    
    # rmtree
    shutil.rmtree('p2')
    
    # move
    shutil.move('p3', 'p2')
            
    Finding Files
    # which
    # tells the path to an executable applicatio
    shutil.which('ls')
            
    Archives
    # get_archive_formats
    # returns archive formats supported on the current system
    shutil.get_archive_formats()
    
    # get_unpack_formats
    # returns unpack formats supported on the current system
    shutil.get_unpack_formats()
    
    # make_archive
    # compress the content in the current directory
    shutil.make_archive('compress', 'tar')
    
    # unpack_archive
    shutil.unpack_archive('compress.tar')
            
    File System Space
    # disk_usage
    # returns a tuple with the total space, the amount currently being used, and the amount remaining free
    total_b, used_b, free_b = shutil.disk_usage('.')
    print(total_b/(2**30), used_b/(2**30), free_b/(2**30))
            
    Reference
  • PyMOTW 3