Shutil Module
The shutil
module in Python is part of the standard library and provides high-level file operations, especially for copying, moving, removing, and archiving files and directories.
It stands for "shell utilities" and is often used when automating tasks like backup scripts, file organizers, deployment, etc.
📦 shutil
Module: Overview
To use it:
🔧 Commonly Used Functions in shutil
✅ 1. shutil.copy(src, dst)
Copies the contents of the file from src
to dst
.
📌 Note: It preserves the file content, but not metadata like permissions.
✅ 2. shutil.copy2(src, dst)
Same as copy()
, but also copies metadata (timestamps, permissions).
✅ 3. shutil.copyfile(src, dst)
Copies content only, both paths must be files (not directories).
✅ 4. shutil.move(src, dst)
Moves a file or directory to a new location (like mv
command in shell).
✅ 5. shutil.rmtree(path)
Deletes an entire directory tree (dangerous! be careful).
✅ 6. shutil.make_archive(base_name, format, root_dir)
Creates an archive (like .zip
, .tar
, etc.) of a directory.
📁 This will create backup.zip
of my_folder
.
✅ 7. shutil.unpack_archive(filename, extract_dir)
Extracts an archive file into a directory.
✅ 8. shutil.getsize(path)
Returns the size in bytes of a file.
✅ 9. shutil.disk_usage(path)
Gives information about total, used, and free disk space.
✅ 10. shutil.which(command)
Returns the path of an executable if found in PATH (like which
command in Unix).
Example: Backing Up a Folder
📌 Summary Table
Function | Description |
---|---|
copy() | Copy file (no metadata) |
copy2() | Copy file with metadata |
copyfile() | Copy file content only |
move() | Move file or folder |
rmtree() | Delete folder recursively |
make_archive() | Create .zip , .tar etc. |
unpack_archive() | Extract archives |
getsize() | Size of file |
disk_usage() | Disk space info |
which() | Path of command/executable |
Comments
Post a Comment