The shutil Module - Copying, Moving, and Deleting
flowchart TD A["copyfile(src, dst)"] --> B["contents only -- dst must be a FILE path"] C["copy(src, dst)"] --> D["contents + permissions"] E["copy2(src, dst)"] --> F["contents + permissions + timestamps"] G["copytree(src, dst)"] --> H["a whole directory, recursively"] I["move(src, dst)"] --> J["rename if possible, else copy+delete"] D --> K["dst may be a directory -- it copies INTO it"] F --> K J --> K L["rmtree(path)"] --> M["deletes recursively, with no confirmation and no undo"]
What shutil is for
Section titled “What shutil is for”shutil (shell utilities) helps with:
- copying files/folders
- moving files
- removing directory trees
Copying files
Section titled “Copying files”import shutil
shutil.copy2("source.txt", "backup_source.txt")copy2 attempts to preserve metadata.
Copying folders
Section titled “Copying folders”import shutil
shutil.copytree("my_folder", "my_folder_backup", dirs_exist_ok=True)Moving files
Section titled “Moving files”import shutil
shutil.move("old/name.txt", "new/name.txt")Deleting folders (danger!)
Section titled “Deleting folders (danger!)”import shutil
shutil.rmtree("danger_folder")Always do a dry run before destructive operations.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading