Recursive delete using Python

Let’s say you have a folder with many (and deep) subfolders, and in each folder, you want to delete ‘Thumbs.db’ file:

#!/usr/bin/env python

import os

def delete(root, name):
    os.unlink(os.path.join(root, name))

def main():
    for root,dir,files in os.walk(os.getcwd()):
        for f in files:
            if f.lower().endswith('.db'):
                if f == 'Thumbs.db':
                    print 'Delete %s' % os.path.join(root, f)
                    delete(root, f)

if __name__=='__main__':
    main()

Save this script as ‘deletethumbs.py’. Go to top folder where you want to delete those ‘thumbs’ and execute it:

cd ~/Music
python ~/deletethumbs.py
Share this...
Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on Pinterest

One thought on “Recursive delete using Python”

Leave a Reply

Your email address will not be published. Required fields are marked *