Request for feedback on my first Python program

Giles Brown giles_brown at hotmail.com
Fri May 30 06:50:17 EDT 2003


Scott Meyers <Usenet at aristeia.com> wrote in message news:<MPG.194096b51af188bb9896f0 at news.hevanet.com>...
> I'm a C++ programmer who's writing his very first Python program.  This
> means the program is going to be gross, and I apologize for that in
> advance.  I don't really have anybody I can show it to for feedback, so I'm
> hoping I can get some comments here.  If there is a better place for me to
> seek guidance, please let me know.
> 
> The program is supposed to read a file containing directory and file names,
> one per line.  (The file can also contain comment and blank lines, which
> should be ignored.)  For each file or directory name, the program should
> print out whether it's a directory, a file, or neither.  That's it.

<code snipped>

As people will have pointed out by now (I am looking at google groups)
you are leaving the '\n' in your lines so that when you print it out
you are ending up with a new line in the middle of your print out.
(Try printing repr(i) within the loop to check).

Anyway just for comparison here's my version (uses 2.2 features):

from   os.path import isdir, isfile
import sys

def main(path):    
    for line in open(path):
        line = line.strip()
        if line[:1] == '#' or not line:
            # Blank or comment
            continue
        print line + " is a",
        if isdir(line): print "directory"
        elif isfile(line): print "file"
        else: print "non-directory and non-file"

if __name__ == '__main__':
    main(*sys.argv[1:])

Notable differences.  
1) I'm processing the lines as a get them from the file.
I could gather them up and process them later, but that would need more memory.
2) I'm using the "*args" calling technique to ensure that an error is reported
if main is called with the wrong number of arguments.  It would print usage,
but for quick and dirty scripts it highlights wrong argument count well enough.
3) I'm using string methods rather than the string module.  String methods are
the future (I hear).
4) I'm using the standard "if __name__ == '__main__':" idiom to indicate the
main function.

Cheers,
Giles Brown




More information about the Python-list mailing list