The useage of python shutil module

python
shutil
Author

Youfeng Zhou

Published

November 22, 2022

Copy and move files and directories

Copy files

shutil.copy(src, dst)

Copy files, but preserve metadata

shutil.copy2(src, dst)

Copy directory tree

shutil.copytree(src, dst)

Move files

shutil.move(src, dst)

Create and unpack archives

Create archives

shutil.make_archive(archive_name,
                    'zip',  # the desired output format
                    root_dir)
# Get a list of supported archive formats
shutil.get_archive_formats()
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('xztar', "xz'ed tar-file"),
 ('zip', 'ZIP file')]

unpack archives

shutil.unpack_archive(archive_name, 
                      extract_dir)