Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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

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

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

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top