Python Practice › OS Module Programs › Program 21
Remove files of one extension
Write a Python program to remove all files with a specific extension from a folder.
Output
['keep.txt']
Approach
- Loop over the folder and remove matching files.
Solution
import os os.makedirs("logs", exist_ok=True)for name in ["a.log", "b.log", "keep.txt"]: open(os.path.join("logs", name), "w").close()for name in os.listdir("logs"): if name.endswith(".log"): os.remove(os.path.join("logs", name))print(os.listdir("logs"))Output
['keep.txt']
Learn the concept
New to this topic? Read the lesson, then come back.