• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Operate on a chosen type of file in a chosen folder and its sub-folders (Python)

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

MaverocK

Registered
Joined
Dec 4, 2013
I created a small tool with Python. It came out of my need to find a certain type of file in a folder and its sub-folders.

Let us say you need to delete every single text file in a folder named "hardforum" and its subfolders Programming, Hardware, Overclock, Auctions, Off-topic:

Overclockers
|__Programming
|__Overclock
|__Hardware
|__Off-topic

The simple python tool I created will allow you to do that. Since the codes are self explanatory, I did not make any comments on the code file.

Download:
https://docs.google.com/file/d/0Bxw3GtGDtHd1RGVIU3lVTGV4N0k/edit

Q: Why are you sharing this file with us?
A: It may give learners an overview, whet their appetite and I can get some comments concerning how I can improve it.
 
I looked it over. I am wondering why you didnt use os.walk?

For example I wrote this function some time ago that serves me quite well

Code:
def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            #the fnmatch module is required (import fnmatch) for this section
            #after finding the file, os.path is used to create an absolute path
            #to the files. The filenames are then returned as a generator
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename


So for example I could do any sort of operation. This particular script gets the mysql version like so:

Code:
for mysqld in find_files(generic_binary_path, "mysql"):
            mysql_version = os.popen(mysqld + " --version").read().split()[4].strip(",")

You could also do something like this:

Code:
def find_files(search_directory, search_for_this, search_type):
    for root, dirs, files in os.walk(search_directory):
        if "file" in search_type:
            search = files
        else:
            search = dirs
        for basename in search:
            #the fnmatch module is required (import fnmatch) for this section
            #after finding the file, os.path is used to create an absolute path
            #to the files. The filenames are then returned as a generator
            if fnmatch.fnmatch(basename, search_for_this):
                filename = os.path.join(root, basename)
                return filename

Which could easily be wrapped into any manner of search (recursive or otherwise)
 
Last edited:
Back