Python Removing Some File Extensions

I'm new to Python, but I got this code to work, and actually do what it intended to do.

However, I am wondering if there is a more efficient way to code this, possibly to increase 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')

There are currently around 8,000 files, and it takes quite a while to process each file and check if it really ends with png or jpg.

+5
source share
2 answers

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 any(currentFile.lower().endswith(ext) for ext in exts):
                os.remove(os.path.join(root, currentFile))
+15
source

If the program works and the speed is acceptable, I would not change it.

unutbu answer.

,

png = "png"
jpg = "jpg"

, .

".png" "png".

extensions = ('.png', '.jpg')

-

if any(currentFile.endswith(ext) for ext in extensions):
    os.remove(currentFile)

.

+1

All Articles