1

actually I read a file like this:

f = open("myfile.txt")
for line in f:
    #do s.th. with the line

what do I need to do to start reading not at the first line, but at the X line? (e.g. the 5.)

4

2 回答 2

9

使用itertools.islice您可以指定启动、停止和步进(如果需要)并将其应用于您的输入文件...

from itertools import islice

with open('yourfile') as fin:
    for line in islice(fin, 5, None):
        pass
于 2013-04-18T13:34:24.747 回答
8

打开的文件对象f是一个迭代器。阅读(并丢弃)前四行,然后继续常规阅读:

with open("myfile.txt", 'r') as f:
    for i in xrange(4):
        next(f, None)
    for line in f:
        #do s.th. with the line
于 2013-04-18T13:32:57.473 回答