0

My input file looks like:

6
*,b,*
a,*,*
*,*,c
foo,bar,baz
w,x,*,*
*,x,y,z
5
/w/x/y/z/
a/b/c
foo/
foo/bar/
foo/bar/baz/

When I use xrange, why does it not adhere to the start, stop, step method?

with open(sys.argv[1], 'r') as f:
  for _ in xrange(0, 7, 1):
    next(f)
  for listPatterns in f:
    print listPatterns.rstrip()

It outputs the text starting at line 7 when in actuality I want it to print line 1 through 7.

David Vasandani
  • 1,840
  • 8
  • 30
  • 53

5 Answers5

4

The code you want is

with open(sys.argv[1], 'r') as f:
  for _ in xrange(0, 7, 1):
    print f.next().rstrip()

The first loop you have is advancing through the file.

colcarroll
  • 3,632
  • 17
  • 25
1

For each item in the iterable (in this case xrange) you're calling next on the file-obj and ignoring the result - either do something with that result, or better yet, make it much clearer:

from itertools import islice
with open('file') as fin:
    for line in islice(fin, 7):
        # do something
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

Er, well, because you told it to skip the first 7 lines? Solution: don't do that.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

it isn't xrange.

you first loop through all of xrange.

then you exit the loop

then you have another loop, acting on the last element

vish
  • 1,046
  • 9
  • 26
0

You can also iterate through the file, without using a proxy iterator

START_LINE = 0
STOP_LINE = 6
with open(sys.argv[1], 'r') as f:
   for i, line in enumerate(f.readlines()):
       if START_LINE <= i <= STOP_LINE:
           print line.rstrip()
       elif i > STOP_LINE: 
           break
Nick T
  • 25,754
  • 12
  • 83
  • 121