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:

import shutil

🔧 Commonly Used Functions in shutil


✅ 1. shutil.copy(src, dst)

Copies the contents of the file from src to dst.

shutil.copy("source.txt", "backup.txt")

📌 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).

shutil.copy2("source.txt", "backup.txt")

✅ 3. shutil.copyfile(src, dst)

Copies content only, both paths must be files (not directories).


shutil.copyfile("file1.txt", "file2.txt")

✅ 4. shutil.move(src, dst)

Moves a file or directory to a new location (like mv command in shell).

shutil.move("old_folder/file.txt", "new_folder/")

✅ 5. shutil.rmtree(path)

Deletes an entire directory tree (dangerous! be careful).

shutil.rmtree("old_backup")

✅ 6. shutil.make_archive(base_name, format, root_dir)

Creates an archive (like .zip, .tar, etc.) of a directory.

shutil.make_archive("backup", "zip", "my_folder")

📁 This will create backup.zip of my_folder.


✅ 7. shutil.unpack_archive(filename, extract_dir)

Extracts an archive file into a directory.

shutil.unpack_archive("backup.zip", "extracted_folder")

✅ 8. shutil.getsize(path)

Returns the size in bytes of a file.

size = shutil.getsize("data.csv")
print(f"Size: {size} bytes")

✅ 9. shutil.disk_usage(path)

Gives information about total, used, and free disk space.

usage = shutil.disk_usage("/")
print(f"Total: {usage.total}, Used: {usage.used}, Free: {usage.free}")

✅ 10. shutil.which(command)

Returns the path of an executable if found in PATH (like which command in Unix).

print(shutil.which("python"))

Example: Backing Up a Folder


import shutil # Copy a file shutil.copy("data.txt", "backup/data_backup.txt") # Move a folder shutil.move("logs", "archive/logs") # Create a zip archive shutil.make_archive("my_project_backup", "zip", "my_project")

📌 Summary Table

FunctionDescription
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

Popular posts from this blog

Python For Application Development MNCST 309 KTU BTech CS Minor 2024 Scheme - Dr Binu V P

Course Details MNCST 309 Python For Application Development

Regular Expression