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

Using the os module,write a function that checks if a back up directory exists.If not,it creates one.Then it copies a specified file to that directory.Explain how the code ensures portability.
  1. Checks if a backup directory exists, and creates it if it doesn't.

  2. Copies a specified file into that directory.

  3. Ensures portability across operating systems by using the os.path module instead of hardcoded path separators.


✅ Code

import os
import shutil def backup_file(source_file, backup_dir="backup"): # Ensure the backup directory exists if not os.path.exists(backup_dir): os.makedirs(backup_dir) # Creates the directory (and any intermediate dirs) # Construct the destination path in a portable way dest_file = os.path.join(backup_dir, os.path.basename(source_file)) # Copy the file shutil.copy2(source_file, dest_file) print(f"File '{source_file}' backed up to '{dest_file}'.")

๐Ÿงช Example Usage


backup_file("data.txt") # Copies 'data.txt' into 'backup/' directory

๐Ÿ” 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

Popular posts from this blog

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

Python For Application Development MNCST309 KTU BTech CS 2024 Scheme Minor Model Question Paper

Course Details MNCST 309 Python For Application Development