Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading