Python Deleting Certain File Extensions

Two picture Two · Oct 20, 2011 · Viewed 13k times · Source

I'm fairly new to Python, but I have gotten this code to work, and in fact, do what it's intended to do.

However, I'm wondering if there is a more efficient way to code this, perhaps to enhance the processing speed.

 import os, glob


def scandirs(path):
    for currentFile in glob.glob( os.path.join(path, '*') ):
        if os.path.isdir(currentFile):
            print 'got a directory: ' + currentFile
            scandirs(currentFile)
        print "processing file: " + currentFile
        png = "png";
        jpg = "jpg";
        if currentFile.endswith(png) or currentFile.endswith(jpg):
            os.remove(currentFile)

scandirs('C:\Program Files (x86)\music\Songs')

Right now, there are about 8000 files, and it takes quite some time to process every file and check if it indeed ends in png or jpg.

Answer

unutbu picture unutbu · Oct 20, 2011

Since you are recursing through subdirectories, use os.walk:

import os

def scandirs(path):
    for root, dirs, files in os.walk(path):
        for currentFile in files:
            print "processing file: " + currentFile
            exts = ('.png', '.jpg')
            if currentFile.lower().endswith(exts):
                os.remove(os.path.join(root, currentFile))