我只需要读取文件的每一行(非常大),所以我不想使用readlines()
。我不确定如何实现迭代器,所以欢迎任何建议。一种可能性是两次调用next()。不太吸引人。
with open(pth_file, 'rw') as pth:
pth.next()
for i,row in enumerate(pth):
# do stuff with row
pth.next()
或创建我自己的迭代器,如
for i, row in enumerate(pth):
if i...
答案 0 :(得分:8)
import itertools
with open(pth_file) as f:
for line in itertools.islice(f, 1, None, 2):
# 1: from the second line ([1])
# None: to the end
# 2: step
# Do something with the line
答案 1 :(得分:1)
您可以使用自定义迭代器:
def iterate(pth):
for i, line in enumerate(pth, 1):
if not i % 2:
yield line