Python Central HubSign in

Automation and Scripting / Phase 1: OS & File System Automation

The shutil Module - Copying, Moving, and Deleting

Learn safe file operations using shutil - copy, move, and remove files/folders.

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.

What shutil is for

shutil (shell utilities) helps with:

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

Copying files

Python
import shutil
 
shutil.copy2("source.txt", "backup_source.txt")

copy2 attempts to preserve metadata.

Copying folders

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

Moving files

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

Deleting folders (danger!)

Python
import shutil
 
shutil.rmtree("danger_folder")

Always do a dry run before destructive operations.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ List Files with os.listdir

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

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

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 โ€“ Write and Read a File

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did