Monday, June 15, 2015

Python3 Scripts

Files from a Path


  1. Returns an array of files.
  2. Param 1: Local Path (either to a file or directory)
  3. Param 2: File Extension to filter on

Usage:
python3 getfiles.py /home/craig/path txt

from __future__ import print_function
from alchemyapi import AlchemyAPI
import json
import argparse  
import os
import fnmatch

## ARGPARSE USAGE  
## <https://docs.python.org/2/howto/argparse.html>  
parser = argparse.ArgumentParser(description="Get Files from Path")  
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")  
group.add_argument("-q", "--quiet", action="store_true")  
parser.add_argument("path", help="The input path for importing. This can be either a file or directory.")  
parser.add_argument("ext", help="The extension to search for.")  
args = parser.parse_args()

 ## RETRIEVE files from filesystem
def getfiles(path) :  

  if len(path) <= 1 :   
    print("!Please Supply an Input File");
    return []  

  try :
    input_path = str(path).strip()
    
    if os.path.exists(input_path) == 0 :
      print ("!Input Path does not exist (input_path = %s)" % input_path)
      return []
   
    if os.path.isdir(input_path) == 0 :
      if args.verbose :
        print ("*Input Path is Valid (input_path = %s)" % input_path)
      return input_path

    matches = []
    for root, dirs, files in os.walk(args.path, topdown=False):
      for filename in fnmatch.filter(files, "*." + args.ext):
        matches.append(os.path.join(root, filename))
             
    if len(matches) > 0 :
      if args.verbose :
        print ("*Found Files in Path (input_path = %s, total-files = %d)" % input_path, len(matches))
      return matches
   
      print ("!No Files Found in Path (input_path = %s)" % input_path)

  except ValueError :
    print ("!Invalid Input (input_path = %s)" % input_path)
  
  return []

files = getfiles(args.path)
print (files)

No comments:

Post a Comment