🧰 Python File Utilities: Your Digital Moving Crew
Imagine you have a team of magical helpers who can copy things, create secret hiding spots, find treasures, and wrap presents beautifully. That’s exactly what Python’s file utilities do for your data!
🎯 The Big Picture
Think of your computer like a giant toy box. Sometimes you need to:
- Copy your favorite toy to share with a friend →
shutil - Create a secret spot to play that disappears when you’re done →
tempfile - Find all toys that match a pattern (like “all red cars”) →
glob - Wrap your message nicely so it fits in a card →
textwrap
Let’s meet each helper!
📦 The shutil Module: Your Moving Truck
shutil = “shell utilities” = your personal moving crew
What Can It Do?
Think of shutil as a moving truck with helpful workers. It can:
- Copy files (like photocopying a drawing)
- Copy whole folders (like moving an entire toy box)
- Move things around (like reorganizing your room)
- Delete folders (cleaning up after a party)
Copy a Single File
import shutil
# Copy a file (like making a photocopy)
shutil.copy('my_photo.jpg', 'backup/')
# Copy with ALL details (timestamps too)
shutil.copy2('my_photo.jpg', 'backup/')
Real-life: Like photocopying your homework. copy2 is the fancy copier that keeps the “made on” date!
Copy an Entire Folder
import shutil
# Copy a whole folder and everything inside
shutil.copytree('my_games/', 'backup_games/')
Real-life: Like picking up your entire toy box and making an exact duplicate!
Move Files or Folders
import shutil
# Move a file to a new home
shutil.move('old_folder/doc.txt', 'new_folder/')
# Rename by moving to same place
shutil.move('old_name.txt', 'new_name.txt')
Real-life: Like physically carrying your toys from bedroom to playroom.
Delete a Folder (Be Careful!)
import shutil
# Delete folder AND everything inside
shutil.rmtree('unwanted_folder/')
⚠️ Warning: This is like throwing away a whole box of toys—no recycling bin, gone forever!
Quick Reference: shutil Functions
| Function | What It Does |
|---|---|
copy(src, dst) |
Copy file only |
copy2(src, dst) |
Copy file + metadata |
copytree(src, dst) |
Copy entire folder |
move(src, dst) |
Move file/folder |
rmtree(path) |
Delete folder tree |
🕳️ Temporary Files: Secret Hideouts
tempfile = Your secret clubhouse that disappears when you leave
Why Do We Need Them?
Sometimes you need a scratch paper:
- Download something, use it, throw it away
- Store data while working, then it vanishes
- Keep secrets that self-destruct
Create a Temporary File
import tempfile
# Create a temp file (auto-deletes later)
with tempfile.NamedTemporaryFile(
mode='w', delete=False
) as tmp:
tmp.write("Secret message!")
print(f"Saved at: {tmp.name}")
Real-life: Like writing on a magic notepad that erases itself!
Create a Temporary Folder
import tempfile
# Create a temp folder
with tempfile.TemporaryDirectory() as tmpdir:
print(f"Playing in: {tmpdir}")
# Do stuff here...
# Folder is GONE when you exit!
Real-life: Like building a sandcastle that the waves wash away when you’re done playing.
Get the Temp Folder Location
import tempfile
# Where do temp files live?
print(tempfile.gettempdir())
# Windows: C:\Users\You\AppData\Local\Temp
# Mac/Linux: /tmp
Temp File Options
import tempfile
# Custom temp file
with tempfile.NamedTemporaryFile(
suffix='.txt', # Ends with .txt
prefix='myapp_', # Starts with myapp_
dir='/custom/path', # Put it here
delete=True # Auto-delete? Yes!
) as tmp:
pass
🔍 glob: The Treasure Hunter
glob = Find files using patterns (like a search party)
The Magic Patterns
Think of glob as a treasure map reader:
*= “anything” (any characters)?= “exactly one mystery character”**= “look everywhere, even in boxes inside boxes”
Find All Files of a Type
import glob
# Find all Python files
python_files = glob.glob('*.py')
print(python_files)
# ['main.py', 'utils.py', 'config.py']
Real-life: “Find me ALL the red blocks!”
Search in Subfolders
import glob
# Find ALL .txt files everywhere
all_texts = glob.glob('**/*.txt', recursive=True)
Real-life: “Look in every room, every drawer, every box for text files!”
Pattern Examples
import glob
# Files starting with "data"
glob.glob('data*')
# → ['data1.csv', 'data_backup.csv']
# Single character wildcard
glob.glob('file?.txt')
# → ['file1.txt', 'fileA.txt']
# Specific characters
glob.glob('[abc]*.py')
# → ['app.py', 'backup.py', 'config.py']
glob vs os.listdir
| glob | os.listdir |
|---|---|
| Uses patterns | Lists everything |
*.py finds Python files |
Then YOU filter |
| Built for searching | Built for listing |
🎁 textwrap: The Gift Wrapper
textwrap = Make your text look pretty and fit nicely
Why Wrap Text?
Imagine writing a letter but your paper is only 40 characters wide. You need to wrap words so they don’t fall off the edge!
Basic Wrapping
import textwrap
long_text = "Python is a wonderful programming \
language that makes coding fun and easy."
# Wrap to 30 characters wide
wrapped = textwrap.wrap(long_text, width=30)
print(wrapped)
# ['Python is a wonderful',
# 'programming language that',
# 'makes coding fun and easy.']
Fill: Wrap and Join
import textwrap
long_text = "Python makes file handling \
easy with its powerful modules."
# Wrap AND join with newlines
result = textwrap.fill(long_text, width=25)
print(result)
# Python makes file
# handling easy with its
# powerful modules.
Real-life: Like folding a paper to fit in an envelope!
Remove Extra Indentation
import textwrap
messy_text = """
This text is
indented weirdly
from the code
"""
clean = textwrap.dedent(messy_text)
print(clean)
# Now it's cleaned up!
Real-life: Like straightening a crooked picture frame.
Shorten Long Text
import textwrap
long_title = "The Complete Guide to Python"
short = textwrap.shorten(
long_title,
width=20,
placeholder="..."
)
print(short) # "The Complete..."
Add a Prefix to Each Line
import textwrap
quote = "Be yourself.\nEveryone else is taken."
# Add "> " to make it look quoted
result = textwrap.indent(quote, "> ")
print(result)
# > Be yourself.
# > Everyone else is taken.
🔗 Putting It All Together
Here’s how these helpers work as a team:
graph LR A["Your Python Script"] --> B["shutil"] A --> C["tempfile"] A --> D["glob"] A --> E["textwrap"] B --> B1["Copy Files"] B --> B2["Move Things"] B --> B3["Delete Folders"] C --> C1["Temp Files"] C --> C2["Temp Folders"] D --> D1["Find by Pattern"] D --> D2["Search Everywhere"] E --> E1["Wrap Text"] E --> E2["Clean Indents"]
Real-World Example: Backup Script
import shutil
import glob
import tempfile
from datetime import datetime
# 1. Find all Python files
py_files = glob.glob('**/*.py', recursive=True)
# 2. Create temp workspace
with tempfile.TemporaryDirectory() as tmpdir:
# 3. Copy each file
for f in py_files:
shutil.copy2(f, tmpdir)
# 4. Create backup archive
today = datetime.now().strftime('%Y%m%d')
shutil.make_archive(
f'backup_{today}',
'zip',
tmpdir
)
# Temp folder auto-cleans!
🎯 Quick Memory Tricks
| Module | Remember As | Key Power |
|---|---|---|
| shutil | Moving Truck 🚚 | Copy, Move, Delete |
| tempfile | Sandcastle 🏖️ | Disappearing storage |
| glob | Detective 🔍 | Pattern matching |
| textwrap | Gift Wrapper 🎁 | Text formatting |
🚀 You’re Ready!
You now have four powerful helpers in your Python toolkit:
- shutil — Moves your data like a professional mover
- tempfile — Creates secret spots that vanish when done
- glob — Finds files using pattern magic
- textwrap — Makes your text beautiful and organized
These tools work together to make file handling feel like magic. Go build something awesome! 🎉
