Python Deleting Certain File Extensions

前端 未结 2 1651
温柔的废话
温柔的废话 2020-12-30 12:18

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 t

相关标签:
2条回答
  • 2020-12-30 12:53

    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))
    
    0 讨论(0)
  • 2020-12-30 13:20

    If the program works and the speed is acceptable, I wouldn't change it.

    Otherwise, you could try unutbu's answer.

    Generally, I would leave away the

    png = "png"
    jpg = "jpg"
    

    stuff as I don't see any purpose in not using the strings directly.

    And better test for ".png" instead of "png".

    An even better solution would be to define

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

    somewhere centally and use that in

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

    .

    0 讨论(0)
提交回复
热议问题