python遍历结构可以是文件,Python:同时遍历许多大文件,获得第k行

As in the title - I have many very large text files (>10GB) that have the same, repetitive structure. I would like to filter some information out so I would like to yield every k-th line from them but iterating over them all at the same time. I have tried itertools: islice and izip, but I cannot put them together...

解决方案

Given that you talk about using itertools.izip(), I'm going to assume you are using Python 2 here.

Use itertools.islice() to facilitate skipping lines from files, and the itertools.izip_longest() function to lazily combine reading in parallel as well as handle files that are shorter:

from itertools import islice, izip_longest

filenames = [fname1, fname2, fname3]

open_files = [open(fname) for fname in filenames]

kth_slice_files = (islice(f, None, None, k) for f in open_files)

try:

for kth_lines in izip_longest(*kth_slice_files, fillvalue=''):

# do something with those combined lines

islice(fileobj, None, None, k) will start at the first line, then skip k - 1 lines to give you the 1 + k, then 1 + 2*k, etc. lines. If you need to start at a later line, replace the first None with that starting value.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值