File System Operations & Management
Automate file moving, renaming, and organization using os and pathlib.
os vs. pathlib
While os is the classic way to handle paths, pathlib provides a modern, object-oriented approach.
Pathlib Basics
from pathlib import Path
# Current directory
cwd = Path.cwd()
# Joining paths
target = cwd / "backups" / "data.txt"
# Checking existence
if target.exists():
print("Found it!")
# Current directory
cwd = Path.cwd()
# Joining paths
target = cwd / "backups" / "data.txt"
# Checking existence
if target.exists():
print("Found it!")
Common Operations
# Create directory
Path("new_folder").mkdir(parents=True, exist_ok=True)
# Iterate over files
for file in Path(".").glob("*.py"):
print(file.name)
# Move/Rename
file.rename("renamed_" + file.name)
Path("new_folder").mkdir(parents=True, exist_ok=True)
# Iterate over files
for file in Path(".").glob("*.py"):
print(file.name)
# Move/Rename
file.rename("renamed_" + file.name)
High-Level Operations (shutil)
For operations like copying and archiving entire trees, use shutil.
import shutil
# Copy a directory
shutil.copytree("source", "dest")
# Create a zip archive
shutil.make_archive("backup", 'zip', "data/")
# Copy a directory
shutil.copytree("source", "dest")
# Create a zip archive
shutil.make_archive("backup", 'zip', "data/")
โ Practice (20 minutes)
- Write a script that finds all
.jpgfiles in a folder and moves them to animagessubfolder. - Modify the script to add a timestamp prefix to each moved file.
- Create a daily backup script that zips your project folder.