Very newbie programming

George Sakkis george.sakkis at gmail.com
Sun Jun 11 10:16:40 EDT 2006


TheSaint wrote:

> Maric Michaud wrote:
>
> > Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
>
> >>
> > begin using more explicit variable names.
>
> Frankly it's a very rooted way of programming, since C64 basic :-)

If by 'rooted' you mean old enough, so is 'goto'... Except perhaps for
iteration variables ("for i in xrange(10)"), always use names that mean
something; you (and anyone else that might have to read your code) will
thank yourself for doing so if you have to go back at this code a few
months later.

> > this will do exactly  the same
> >
> > for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop'
> > in e) :
> >     for line in icon_file :
> >         if  'URL=/media' in line :
> >             icon = icon.name
> >             dvc = line[11:-1]
> >             break
> >
> A simple question, how do I'll get out of all loops, once found the right
> result?

You can set a boolean "found" flag to False, make it True in the if
block, check it in the outer loop and break if it is True. For this
case though I'd use the fileinput module to iterate over the lines of
all files directly (http://docs.python.org/lib/module-fileinput.html):

from fileinput import FileInput

instram = FileInput([dskt+e for e in os.listdir(dskt) if 'desktop' in
e])
for line in instream:
    if  'URL=/media' in line :
        icon = instream.filename()
        dvc = line[11:-1]
        break

Btw, you can delete a file or directory with os.unlink and os.rmdir,
respectively; no need for os.system.

George




More information about the Python-list mailing list