Python Practice › OS Module Programs › Program 22
Backup sorted by extension
Write a Python backup program that copies every file into a folder named after its extension.
Output
csv ['d.csv'] py ['a.py', 'b.py'] txt ['c.txt']
Approach
- Walk the source, compute the extension and copy into
backup/<ext>/.
Solution
import osimport shutil os.makedirs("project/docs", exist_ok=True)for path in ["project/a.py", "project/b.py", "project/docs/c.txt", "project/d.csv"]: with open(path, "w") as f: f.write("x") for folder, _, files in os.walk("project"): for name in files: ext = os.path.splitext(name)[1].lstrip(".") or "no_ext" target = os.path.join("backup", ext) os.makedirs(target, exist_ok=True) shutil.copy2(os.path.join(folder, name), target) for ext in sorted(os.listdir("backup")): print(ext, sorted(os.listdir(os.path.join("backup", ext))))Output
csv ['d.csv'] py ['a.py', 'b.py'] txt ['c.txt']
Line by line
Lines 9-14
Every file found by os.walk is copied into a folder for its extension; files without one go to “no_ext”.
Learn the concept
New to this topic? Read the lesson, then come back.