Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Terry Reedy Newsgroups: comp.lang.python Subject: Re: Lookahead while doing: for line in fh.readlines(): Date: Sat, 27 Feb 2016 06:46:24 -0500 Lines: 34 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de hssyL4drtGwBVO+F8J3pRQyBurhxwZDWR+kenLUtGPnQ== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'python3': 0.05; 'lines.': 0.07; 'repeated': 0.07; 'returned.': 0.07; 'block.': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'subject:while': 0.09; 'jan': 0.11; '4:39': 0.16; 'received:80.91.229.3': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'reedy': 0.16; 'slow,': 0.16; 'splits': 0.16; 'temp': 0.16; 'wrote:': 0.16; 'byte': 0.18; 'first.': 0.18; 'pointer': 0.18; 'trying': 0.22; 'am,': 0.23; 'somewhere': 0.24; 'header:In-Reply- To:1': 0.24; 'header:User-Agent:1': 0.26; "doesn't": 0.26; 'header:X-Complaints-To:1': 0.26; 'skip:# 10': 0.27; 'least': 0.27; 'readline': 0.29; 'character': 0.29; "i'm": 0.30; 'file': 0.34; 'something': 0.35; 'too': 0.36; 'should': 0.36; 'instead': 0.36; 'data.': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'end': 0.39; 'why': 0.39; 'to:addr:python.org': 0.40; 'some': 0.40; 'entire': 0.61; 'received:96': 0.63; 'subject:doing': 0.84; 'received:fios.verizon.net': 0.91 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: pool-96-227-207-81.phlapa.fios.verizon.net User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.6.0 In-Reply-To: X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21rc2 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:103578 On 2/27/2016 4:39 AM, Veek. M wrote: > I want to do something like: > > #!/usr/bin/env python3 > > fh = open('/etc/motd') > for line in fh.readlines(): > print(fh.tell()) > > why doesn't this work as expected.. fh.readlines() should return a > generator object and fh.tell() ought to start at 0 first. Not after you have already read some data. Readlines() reads the entire file and splits it into lines. readline reads at least a single block. Reading a single byte or character at a time looking for /n would be too slow, so even after readline, the file pointer will be somewhere past the end of the last line returned. > Instead i get the final count repeated for the number of lines. > > What i'm trying to do is lookahead: > #!whatever > > fh = open(whatever) > for line in fh.readlines(): > x = fh.tell() > temp = fh.readline() > fh.seek(x) > -- Terry Jan Reedy