Fix Python – Deleting all files in a directory with Python

Question

Asked By – slh2080

I want to delete all files with the extension .bak in a directory. How can I do that in Python?

Now we will see solution for issue: Deleting all files in a directory with Python


Answer

Via os.listdir and os.remove:

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))

Using only a single loop:

for f in os.listdir(mydir):
    if not f.endswith(".bak"):
        continue
    os.remove(os.path.join(mydir, f))

Or via glob.glob:

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:
    os.remove(f)

Be sure to be in the correct directory, eventually using os.chdir.

This question is answered By – miku

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0