[prev in list] [next in list] [prev in thread] [next in thread] 

List:       python-list
Subject:    Re: Making a copy (not reference) of a file handle,
From:       Peter Otten <__peter__ () web ! de>
Date:       2007-08-17 18:23:32
Message-ID: fa4p36$5gj$02$1 () news ! t-online ! com
[Download RAW message or body]

Shawn Milochik wrote:

> How can I check a line (or two) from my input file (or stdin stream)
> and still be able to process all the records with my function?

One way:

from itertools import chain
firstline = instream.next()
head = [firstline]

# loop over entire file
for line in chain(head, instream):
    process(line)


You can of course read more than one line as long as you append it to the
head list. Here's an alternative:

from itertools import tee
a, b = tee(instream)

for line in a:
    # determine file format,
    # break when done

# this is crucial for memory efficiency
# but may have no effect in implementations
# other than CPython
del a 

# loop over entire file
for line in b:
    # process line


Peter

-- 
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic