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
import shutil
Copy a File
Use shutil.copy().
import shutil
shutil.copy("notes.txt", "notes_backup.txt")
This creates a copy of the file.
Move a File
Use shutil.move().
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().
import shutil
shutil.copytree("photos", "photos_backup")
This copies the whole folder and everything inside it.
Delete a Folder
Use shutil.rmtree().
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
import shutil
shutil.move("report.txt", "backup/final_report.txt")
Check If File Exists First
Combine with os.path.exists().
import shutil
import os
if os.path.exists("notes.txt"):
shutil.copy("notes.txt", "copy.txt")
else:
print("File not found")
Output
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.
import shutil
shutil.copy("data.txt", "backup.txt")
Mini Challenge
Build a backup tool.
Steps:
- Create a folder named
backup - Copy
notes.txtinto the folder - Rename it to
notes_old.txt
Hint:
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
- What does
shutil.copy()do? - What does
shutil.move()do? - What does
shutil.copytree()copy? - 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.