Remove files of one extension

EasyOS Module Programs · 21 of 49

Write a Python program to remove all files with a specific extension from a folder.

Advertisement
Output
['keep.txt']

Approach

  1. Loop over the folder and remove matching files.

Solution

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

More os module programs

← All 49 OS Module Programs

Leave a Comment