Newbie looking for feedback

Alex Martelli aleaxit at yahoo.com
Fri Sep 15 06:38:31 EDT 2000


"Tyler Eaves" <tyler at tylereaves.com> wrote in message
news:39c1aa1e.6407246 at news.geeksnet.com...
> On Fri, 15 Sep 2000 04:43:52 GMT, David Lees
> <debl.spamnono at world.std.com> wrote:
>
> Still sorta a newbie myself, but here's my take.
>
> in=open('C:\\foo.txt','r').readlines()
> #Opens the input file and reads each line into a list entry
> out=open('C:\\bar.txt','w')
> #Open output file
> for x in in[:]:
> #Loop once for every line
> if len(x)>1:
> #Test to see if the line has anything....
> out.write(x)
> #It does! Write it!
>
> #Done!
> (5 lines of active code that gets the job done!)

Excellent -- except that it shouldn't work as written, because
"in" is a reserved word.  Still, it's easy to fix, with a few
nice little touches:

out = open(r'C:\bar.txt', 'w')
for line in open(r'c:\foo.txt').readlines():
    if len(line)>1:
        out.write(line)
out.close()

Notes:
    we can use the r'string' notation to let backslashes (\) be
    used in a platform-natural way on Windows, without doubling
    them up (we could also write 'c:/foo.txt', etc);

    we don't need an explicitly named object for the input-file,
    as we just get its list-of-lines in the for statement itself;
    thus, we don't need to close it, either (it is automatically
    closed by the Python runtime as soon as possible & convenient).

> >Two questions.  First, I have written a real simple Python routine to
> >remove blank lines from a text file.  The code below works but...
> >
> >1. I am sure this can be written much more simply, any hints?

See above: exploit the "for line in ...readlines()" idiom, use
the simplest of equivalent tests, here len(line)>1 rather than
line[0]!='\n' (not much of a difference, but some), use either
r'...' or /-notation for Windows filenames.  The first of these
is the one that makes a real difference, but the other may be
nice little touches of readability/simplicity.


> >2. Could someone point me to documentation or tell me how to use IDLE
> >under Windows to single step through the code.  It was a pain debugging
> >by executing the whole script as a run module command to IDLE.

(At least in IDLE 0.6, coming with the current 2.0b1 of Python; I
don't recall previous versions very well, particularly since I had
been using mostly PythonWin of late...): from main menu Debug, pick
the Debugger menuitem.  You'll see 4 checkboxes for what you'll want
to look at (stack, source, locals, globals) -- pick them appropriately --
and 5 buttons (Go/Step/Over/Out/Quit) currently disabled as nothing
is loaded.  Now from the interactive IDLE Python shell,
    import mymodule
will load your mymodule.py script and let you interact with it
through the debugger.


Alex






More information about the Python-list mailing list