Introduction to Python Programming

 

Assignment 2

 

 

 

 

 

 


 

#!/usr/bin/env python

 

# standard python modules

import sys

import os

import getopt

 

# my directory browser module

from dirb import *

 

def usage(name):

    print """

   

Usage: %s [-h|--help] [-r|--recursive] [<directory path>] [[<extension>] [<extension>] ...]

 

Arguments:

    <directory path>            directory to list files, if ommitted then use current directory

    <extension> <extension> ... extension filter list

    

Options:

    -h|--help

    -r|--recursive              search all subdirectories to print file list

    """%name

   

def main():

   

# process command line arguments

 

    try:

        opts, args = getopt.getopt(sys.argv[1:], 'hr', ['help','recursive'])

    except getopt.GetoptError:

        print 'Error: invalid argument'

        usage(sys.argv[0])

        sys.exit(1)

 

# parse options

 

    reSw = False    # recursive directory listing is false by default

    for o, a in opts:

            if o in ('-h', '--help'):

                usage(sys.argv[0])

                sys.exit()

            if o in ('-r', '--recursive'):

                reSw = True

 

# current directory is default if no directory argument is given

    dirPath = os.getcwd()

    extFilters = []

   

# parse arguments

 

    if len(args) > 0:

        if (os.path.isdir(args[0])):

            dirPath = args[0]

            extFilters = args[1:]

        else:

            extFilters = args

 

# if reSw is true, then call dirb in recursive mode using walk

    if reSw:

        os.path.walk(dirPath, dirb, extFilters)

# otherwise just call dirb directly

    else:

        dirb(extFilters, dirPath, os.listdir(dirPath))

       

   

if __name__ == '__main__':

    main()

 

 

 

#!/usr/bin/env python

 

import os

import time

 

def dirb(ext, dirName, files):

    print '\n'

    print '*** Directory: %s' % dirName

 

    for thisFile in files:

        if ext:

            thisExt = os.path.splitext(thisFile)[1][1:]

            if (not (thisExt in ext)):

                continue

           

        try:

            mTime = os.path.getmtime(thisFile)

        except:

            mTime = 0

        timeStr = time.asctime(time.gmtime(mTime))

        print '     %s  %s' % (thisFile.ljust(40), timeStr.ljust(30))

       

    return