Deleting all files in a directory with Python

slh2080 picture slh2080 · Jan 3, 2010 · Viewed 235.4k times · Source

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

Answer

miku picture miku · Jan 3, 2010

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.