Skip to content

The shutil Module - Copying, Moving, and Deleting

What shutilshutil is for

shutilshutil (shell utilities) helps with:

  • copying files/folders
  • moving files
  • removing directory trees

Copying files

copy_file.py
import shutil
 
shutil.copy2("source.txt", "backup_source.txt")
copy_file.py
import shutil
 
shutil.copy2("source.txt", "backup_source.txt")

copy2copy2 attempts to preserve metadata.

Copying folders

copy_tree.py
import shutil
 
shutil.copytree("my_folder", "my_folder_backup", dirs_exist_ok=True)
copy_tree.py
import shutil
 
shutil.copytree("my_folder", "my_folder_backup", dirs_exist_ok=True)

Moving files

move_file.py
import shutil
 
shutil.move("old/name.txt", "new/name.txt")
move_file.py
import shutil
 
shutil.move("old/name.txt", "new/name.txt")

Deleting folders (danger!)

remove_tree.py
import shutil
 
shutil.rmtree("danger_folder")
remove_tree.py
import shutil
 
shutil.rmtree("danger_folder")

Always do a dry run before destructive operations.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ List Files with os.listdir

Exercise 2 โ€“ Join Paths with os.path.join

Exercise 3 โ€“ Write and Read a File

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did