CodingNic

Files, Errors, and Automation

File Management with shutil

Files, Errors, and Automation 28 min read

File Management with shutil

File Management with shutil

Sometimes you need to do more than read or write files.

You may want to:

  • Copy files
  • Move files
  • Rename folders
  • Delete folders
  • Make backups

Python can do this with the shutil module.

What Is shutil?

shutil is a built-in Python module for high-level file and folder operations.

It helps manage files faster and easier.

Import shutil

python
import shutil

Copy a File

Use shutil.copy().

python
import shutil

shutil.copy("notes.txt", "notes_backup.txt")

This creates a copy of the file.

Move a File

Use shutil.move().

python
import shutil

shutil.move("notes.txt", "archive/notes.txt")

This moves the file to another folder.

It can also rename while moving.

Copy a Folder

Use shutil.copytree().

python
import shutil

shutil.copytree("photos", "photos_backup")

This copies the whole folder and everything inside it.

Delete a Folder

Use shutil.rmtree().

python
import shutil

shutil.rmtree("old_files")

This removes the folder and everything inside it.

Important Warning

Be careful with rmtree().

Deleted files may be hard to recover.

Move and Rename Together

python
import shutil

shutil.move("report.txt", "backup/final_report.txt")

Check If File Exists First

Combine with os.path.exists().

python
import shutil
import os

if os.path.exists("notes.txt"):
    shutil.copy("notes.txt", "copy.txt")
else:
    print("File not found")

Output

text
File not found

(Only if the file is missing.)

Common Beginner Errors

Source File Missing

The file you want to copy or move must exist.

Destination Folder Missing

The target folder must exist first.

Copytree Destination Exists

copytree() usually needs a new folder name.

Code Along

Copy data.txt into backup.txt.

python
import shutil

shutil.copy("data.txt", "backup.txt")

Mini Challenge

Build a backup tool.

Steps:

  • Create a folder named backup
  • Copy notes.txt into the folder
  • Rename it to notes_old.txt

Hint:

text
backup/notes_old.txt

Expected result:

A copied file inside the backup folder.

Real World Use Case

Programs use shutil for backups, file organizers, archive tools, installers, and moving reports.

Quiz

  1. What does shutil.copy() do?
  2. What does shutil.move() do?
  3. What does shutil.copytree() copy?
  4. Why be careful with shutil.rmtree()?

Assignment

Create a folder named archive. Move one file into it using shutil.move().

Summary

You learned how to use shutil to copy files, move files, copy folders, delete folders, and build backup tools.