Python

NAVIGATION
CATEGORIES
REFERRENCE
LINKS
  • For loop question

    0 answers - 2566 bytes - related search similar search Add To My Delicious Add To My Stumble Upon Add To My Google Mark Add To My Facebook Add To My Digg Add To My Reddit

    Smith, Jeff wrote:
    At least with Python there's only one obvious way to do something :-)
    Yeah, right. A couple of minutes reading comp.lang.python will disabuse
    you of that notion :-)
    I'll see your simplification and raise (or lower) you a line.
    Why not simply:
    for item in file('hosts.txt'):
    tn = telnetlib.Telnet(item.strip())
    If you are willing to depend on the runtime to close the file that is
    fine. If you want to close it yourself you have to keep a reference to
    the open file.
    For short Python scripts I usually allow the runtime to close the file.
    For longer programs and anything written in Jython (which has different
    garbage collection behaviour) I usually use an explicit close().
    Kent
    Jeff
    Message
    From: tutor-bounces (AT) python (DOT) org [mailto:tutor-bounces (AT) python (DOT) org]
    Behalf Kent Johnson
    Sent: Wednesday, May 10, 2006 5:52 AM
    Cc: tutor (AT) python (DOT) org
    Subject: Re: [Tutor] For loop question
    w chun wrote:
    >another thing is that if the host file is large, you may wish to
    >iterate through the file one line at a time with a list comprehension
    >to do the stripping for you:
    >>

    >HostFile = open("hosts.txt", 'r')
    >for item in [x.strip() for x in HostFile]:
    >:

    Why is this better when the file is large? It still creates a list with
    all lines in it.
    >if you are using Python 2.4+, you can come up with an even better
    >solution by using a generator expression that does lazier, ad hoc
    >evaluation:
    >>

    >HostFile = open("hosts.txt", 'r')
    >for item in (x.strip() for x in HostFile):
    >:
    >>

    >this one will read and strip one line from the file as you process it
    >while the previous solution still needs to come up with the entire
    >list of stripped hosts before the for-loop can begin.

    I would use this, it avoids reading the entire file at once and IM is
    clear and straightforward:
    HostFile = open('hosts.txt')
    for item in HostFile:
    item = item.strip()
    or even
    HostFile = open('hosts.txt')
    for item in HostFile:
    tn = telnetlib.Telnet(item.strip())
    Kent
    Tutor maillist - Tutor (AT) python (DOT) org
    Tutor maillist - Tutor (AT) python (DOT) org

Re: For loop question


max 4000 letters.
Your nickname that display:
In order to stop the spam: 3 + 2 =
QUESTION ON "Python"

EMSDN.COM