Monday, February 3, 2020

Python - get all the files in specified folders


This function below returns a list of file under current directory based on the file extension.
e.g. 
file_list = filebrowser(".zip")


def filebrowser(ext=""):
    "Returns files with an extension"    return [f for f in glob.glob(f"*{ext}")]


This function below return specified files in a list.

import os
from fnmatch import fnmatch

# 28 states

state_list = ['al', 'ar', 'ca', 'co', 'fl', 'id', 'ks', 'ky', 'la', 
'mi', 'mo', 'ms', 'mt', 'nd', 'ne', 'nm', 'nv', 'ny', 'oh', 'ok', 
'pa', 'sd', 'tn', 'tx', 'ut', 'va', 'wv', 'wy']
for state in state_list:
    root = os.path.join(os.path.dirname(os.path.abspath(__file__)), state)
    pattern = "*.py"    
    exclude_files = ['__init__', '_unit_test']
    for path, subdirs, files in os.walk(root):
        for name in files:
            if fnmatch(name, pattern) 
               and all(str(name).find(sub_name) == -1 for sub_name in exclude_files):
                print(os.path.join(path, name))

No comments:

Post a Comment