如何在python中的X行开始读取?

2024-04-19 01:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

实际上我读过这样的文件:

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

我需要做什么来开始阅读不是在第一行,而是在X行?(例如5)


Tags: 文件theintxtforwithlineopen
2条回答

打开的文件对象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

如果需要,可以使用itertools.islice指定start、stop和step,并将其应用于输入文件。。。在

from itertools import islice

with open('yourfile') as fin:
    for line in islice(fin, 5, None):
        pass

相关问题 更多 >