加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python同时逐行分析两个大文件

发布时间:2020-12-20 11:35:27 所属栏目:Python 来源:网络整理
导读:我正在尝试分析两个±6 GB的文件.我需要同时分析它们,因为我需要同时使用两行(每个文件一行).我试着这样做: with open(fileOne,"r") as First_file: for index,line in enumerate(First_file): # Do some stuff here with open(fileTwo,"r") as Second_file
我正在尝试分析两个±6 GB的文件.我需要同时分析它们,因为我需要同时使用两行(每个文件一行).我试着这样做:

with open(fileOne,"r") as First_file:
    for index,line in enumerate(First_file):

        # Do some stuff here

    with open(fileTwo,"r") as Second_file:
        for index,line in enumerate(Second_file):

            # Do stuff here aswell

问题是在第二个“with open”循环开始于文件的开头.因此,分析将花费很长时间.我也试过这个:

with open(fileOne,"r") as f1,open(fileTwo,"r") as f2:
    for index,(line_R1,line_R2) in enumerate(zip(f1,f2)):

问题是两个文件都直接加载到内存中.我需要每个文件中的相同行.正确的是:

number_line%4 == 1

这将给出第2,5,9,13行等.我需要两个文件中的那些行.

是否有更快的方式和更高效的内存方式?

解决方法

在Python 2中,使用 itertools.izip()来防止文件被加载到内存中:

from itertools import izip

with open(fileOne,line_R2) in enumerate(izip(f1,f2)):

内置的zip()函数确实会将两个文件对象完全读入内存,izip()一次检索一行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读