Rename with os.renames()

EasyOS Module Programs · 40 of 49

Write a Python program to move a file into new nested folders with os.renames().

Advertisement
Output
True False

Approach

  1. renames creates missing folders on the new path and removes empty ones on the old path.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment