Python Practice › OS Module Programs › Program 40
Rename with os.renames()
Write a Python program to move a file into new nested folders with os.renames().
Output
True False
Approach
renamescreates missing folders on the new path and removes empty ones on the old path.
Solution
import os os.makedirs("drafts/2025", exist_ok=True)open("drafts/2025/plan.txt", "w").close()os.renames("drafts/2025/plan.txt", "archive/2026/plan.txt")print(os.path.exists("archive/2026/plan.txt"), os.path.exists("drafts"))Output
True False
Line by line
Line 5
The now-empty “drafts” folders are removed automatically.
Learn the concept
New to this topic? Read the lesson, then come back.