[英]How to read in only every second line of file?
我只需要讀文件的第二行(非常大),所以我不想使用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...
使用itertools.islice
:
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
您可以使用自定義迭代器:
def iterate(pth):
for i, line in enumerate(pth, 1):
if not i % 2:
yield line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.