← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Shutil Module

Topic: System

Advertisement

Introduction

Shutil provides high-level file operations like copying and archiving.

Copy Operations

import shutil

# Copy file (metadata)
shutil.copy("source.txt", "dest.txt")

# Copy with permissions
shutil.copy2("source.txt", "dest.txt")

# Copy directory
shutil.copytree("src_dir", "dst_dir")

# Copy file to directory
shutil.copy("file.txt", "dest_dir/")

Move and Remove

import shutil

# Move file or directory
shutil.move("source", "dest")

# Remove directory tree
shutil.rmtree("directory")

# Make archive
shutil.make_archive("backup", "zip", "directory")

Disk Usage

import shutil

# Get disk usage
usage = shutil.disk_usage("/")
print(usage.total, usage.used, usage.free)

# Find largest files
total, used, free = shutil.disk_usage(".")

Practice Problems

  1. Create backup of directory
  2. Implement recursive file copier
  3. Compress directory to tar
  4. Find duplicate files
  5. Clean up old files by age

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →