for loop: weird behavior

Terry Reedy tjreedy at udel.edu
Fri May 4 16:47:07 EDT 2012


On 5/4/2012 4:33 PM, ferreirafm wrote:
> Hi there,
> I simply can't print anything in the second for-loop bellow:
>> #########################################
> #!/usr/bin/env python
>> import sys
>> filename = sys.argv[1]
> outname = filename.split('.')[0] + '_pdr.dat'
> begin = 'Distance distribution'
> end = 'Reciprocal'
> first = 0
> last = 0
> with open(filename) as inf:
> for num, line in enumerate(inf, 1):
> #print num, line
> if begin in line:
> first = num
> if end in line:
> last = num

The file pointer is now at the end of the file. As an iterator, the file 
is exhausted. To reiterate, return the file pointer to the beginning 
with inf.seek(0).
> for num, line in enumerate(inf, 1):
> print 'Ok!'
> print num, line
> if num in range(first + 5, last - 1):
> print line
> print first, last
> print range(first + 5, last - 1)

-- 
Terry Jan Reedy


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /