Calling rm from subprocess using wildcards does not remove the files

mythander889 picture mythander889 · Jun 14, 2012 · Viewed 14.3k times · Source

I'm trying to build a function that will remove all the files that start with 'prepend' from the root of my project. Here's what I have so far

def cleanup(prepend):
    prepend = str(prepend)
    PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
    end = "%s*" % prepend
    cmd = 'rm'
    args = "%s/%s" % (PROJECT_ROOT, end)
    print "full cmd = %s %s" %(cmd, args)
    try:
        p = Popen([cmd, args],  stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate()[0]
        print "p", p
    except Exception as e:
        print str(e)

I'm not having any luck -- it doesn't seem to be doing anything. Do you have any ideas what I might be doing wrong? Thank you!

Answer

Levon picture Levon · Jun 14, 2012

Would you consider this approach using os.remove() to deleting files instead of rm:

import os
os.remove('Path/To/filename.ext')

Update (basically moving my comment from below into my answer):

As os.remove() can't handle wildcards on its own, using the glob module to help will yield a solution as repeated verbatim from this SO answer:

import glob
import os
for fl in glob.glob("E:\\test\\*.txt"):
    #Do what you want with the file
    os.remove(fl)