Request for feedback on my first Python program

Achim Domma domma at procoders.net
Fri May 30 03:17:40 EDT 2003


"Scott Meyers" <Usenet at aristeia.com> wrote in message
news:MPG.194096b51af188bb9896f0 at news.hevanet.com...
> hoping I can get some comments here.  If there is a better place for me to
> seek guidance, please let me know.

I think you have found the right place! ;-)

> Here's the code; you may want to hold your nose:
[...]

Here is how I would have written your code. Might not be perfect, but should
give you some ideas on how to use python:

from __future__ import generators
from os.path import isdir,isfile,basename
from sys import argv, exit

if len(argv)!=2:
    print "Usage: " + basename(argv[0]) + " [file]"
    exit(1)

def meaningfulLines(lines):
    # the file object passed can be used as iterator
    # it iterates over the lines in the file
    for line in lines:
        # strip removes the whitespaces
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        # see http://www.python.org/doc/2.2.2/whatsnew/node5.html for
        # details about generators
        yield line

# meaningfulLines returns a generator which can be used
# to iterate over
for line in meaningfulLines(file(argv[1])):
    print line,"is a",
    if isdir(line): print "directory"
    elif isfile(line): print "file"
    else: print "non-directory and non-file"

The output is as expected, so I don't know why your code does not work for
you.

regards,
Achim

PS.: Very nice to see more and more top C++ expert interested in Python!







More information about the Python-list mailing list