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 |
Checks if a backup directory exists, and creates it if it doesn't.
-
Copies a specified file into that directory.
-
Ensures portability across operating systems by using the
os.path
module instead of hardcoded path separators.
✅ Code
๐งช Example Usage
๐ Explanation of Portability
This code is portable across operating systems (Windows, Linux, macOS) because:
✅
os.path.join(...)
: Joins paths using the correct separator (\
on Windows,/
on Unix-like systems), avoiding hardcoded paths.-
✅
os.makedirs(...)
: Creates directories recursively and works across platforms. -
✅
shutil.copy2(...)
: Copies the file along with metadata (like modification time) and works reliably on all OSes. -
❌ Avoids using
\\
or/
directly in paths, which may break on different platforms
Comments
Post a Comment