[英]How to read in only every second line of file?
I need to read in only every second line of a file (which is very big) so I don't want to use readlines()
. 我只需要读文件的第二行(非常大),所以我不想使用
readlines()
。 I'm unsure how to implement the iterator so any suggestions are welcome. 我不确定如何实现迭代器,因此欢迎提出任何建议。 One possibility is to call next() twice.
一种可能性是调用next()两次。 Not very appealing.
不太吸引人。
with open(pth_file, 'rw') as pth:
pth.next()
for i,row in enumerate(pth):
# do stuff with row
pth.next()
Or creating my own iterator like 或者创建自己的迭代器,例如
for i, row in enumerate(pth):
if i...
Using itertools.islice
: 使用
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
You can use a custom iterator: 您可以使用自定义迭代器:
def iterate(pth):
for i, line in enumerate(pth, 1):
if not i % 2:
yield line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.