Skip to content

The shutil Module - Copying, Moving, and Deleting

diagram which shutil function keeps what mermaid
The four copying functions differ in what they carry across and what they accept as a destination. copyfile is bytes only and needs a filename; copy adds permissions and will accept a directory; copy2 additionally preserves the timestamps, which is what you want when the mtime is meaningful. Choosing the wrong one is how a backup ends up with every file dated today.

shutil (shell utilities) helps with:

  • copying files/folders
  • moving files
  • removing directory trees
copy_file.py
import shutil
 
shutil.copy2("source.txt", "backup_source.txt")

copy2 attempts to preserve metadata.

copy_tree.py
import shutil
 
shutil.copytree("my_folder", "my_folder_backup", dirs_exist_ok=True)
move_file.py
import shutil
 
shutil.move("old/name.txt", "new/name.txt")
remove_tree.py
import shutil
 
shutil.rmtree("danger_folder")

Always do a dry run before destructive operations.

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading