Request for feedback on my first Python program

Paul Rubin http
Fri May 30 03:29:36 EDT 2003


Scott Meyers <Usenet at aristeia.com> writes:

> 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.
> 
> Here's the code; you may want to hold your nose:
> 
>   import sys
>   import os
>   import string
>   
>   # Error status codes
>   BadInvocation = 1
>   
>   def usage(programName):
>     print "Usage: " + os.path.basename(programName) + " [file]"
>     sys.exit(BadInvocation)
>   
>   # Take a list of strings, return an equivalent list where the following
>   # strings have been removed:
>   # - those with no non-whitespace characters
>   # - those whose first non-whitespace character is a "#"

>   def getMeaningfulLines(lines): ...
>    ...

I'd write that function like this:

   def is_meaningful(line):
     # return 1 if line is meaningful, 0 otherwise
     line = line.strip()     # remove leading and trailing whitespace
     return (line and line[0] != '#')

And then

>   lines = getMeaningfulLines(open(sys.argv[1]).readlines())

becomes

    # read the lines and discard the non-meaningful ones
    lines = filter(is_meaningful, open(sys.argv[1]).readlines())

For

>   # if this language had a main(), it'd be here...
>   if len(sys.argv) != 2: usage(sys.argv[0])

Generally I like to supply a main() anyway and call it:

def main():
  bla blah
  bla blah

main()

> Aside from being ugly (how do I get rid of the newline that follows each
> directory or file name?), the problem is that the first entry IS a
> directory and the second one IS a file.  So clearly I'm doing something
> wrong.  Any idea what it is?

Maybe there was an extra space or something.




More information about the Python-list mailing list