Request for feedback on my first Python program

Stephen D Evans sde at recombinant.demon.co.uk
Fri May 30 08:15:31 EDT 2003


"Scott Meyers" <Usenet at aristeia.com> wrote in message
<snip>

String twiddling can get difficult to maintain. In your program only a
single strip() is required to remove leading and trailing whitespace.

Regular expressions work "out of the box" in Python. The "re" module
is well documented. Your getMeaningfulLines() function can be replaced by
a test for a match object:


# Tested on Python 2.2.2 and Python 2.3b1
import sys
import os
import re

# Error status codes
BADINVOCATION = 1

def usage(programName):
    print "Usage: " + os.path.basename(programName) + " [file]"
    sys.exit(BADINVOCATION)

def test(filename):
    valid_pattern = re.compile('\s*[^#\s]')

    #Python 2.3 use
    #for line in file(filename, 'rt'):

    for line in file(filename, 'rt').xreadlines():
        if valid_pattern.match(line): # meaningful line
            line = line.strip()
            type = os.path.isdir(line) and "directory"
            type = type or os.path.isfile(line) and "file"
            type = type or "non-directory and non-file"
            print line, "is a ", type

if __name__ == '__main__':
    if len(sys.argv) != 2:
        usage(sys.argv[0])
    test(sys.argv[1])






More information about the Python-list mailing list