문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top