Python – How to delete all text files in a given directory

Question:

I would Like a way to delete all text files in a directory. There are other files in the directory as well so I would only like to delete the .txt files. How would I do this?

Asked By: PyMan

||

Answers:

You might combine glob.glob with os.remove to get all .txt files deleted in current working directory as follow

import glob
import os
for filename in glob.glob("*.txt"):
    os.remove(filename)
Answered By: Daweo
for file in os.listdir(dir):
    if file.endswith('.txt'):
        os.remove(os.path.join(dir, file))

EDIT: For clarity, fill in your own dir name — do not use dir as variable names.

Answered By: cornifer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.