Python - 阅读巨大的文件

时间:2017-04-19 13:19:35

标签: python

我有以下代码尝试处理包含多个xml元素的大文件。

from shutil import copyfile
files_with_companies_mentions=[]
# code that reads the file line by line
def read_the_file(file_to_read):
    list_of_files_to_keep=[]
    f = open('huge_file.nml','r')
    lines=f.readlines()
    print("2. I GET HERE ")
    len_lines = len(lines)
    for i in range(0,len(lines)):
        j=i
        if '<?xml version="1.0"' in lines[i]:
            next_line = lines[i+1]
            write_f = open('temp_files/myfile_'+str(i)+'.nml', 'w')
            write_f.write(lines[i])
            while '</doc>' not in next_line:
                write_f.write(next_line)
                j=j+1
                next_line = lines[j]
            write_f.write(next_line)    
            write_f.close()
            list_of_files_to_keep.append(write_f.name)
    return list_of_files_to_keep

该文件超过700 MB,超过2000万行。有没有更好的方法来处理它?<​​/ p>

正如您所看到的,我需要使用指示符变量(例如i)来引用上一行和下一行。

我面临的问题是它很慢。每个文件需要1个多小时,我有多个这样的文件。

3 个答案:

答案 0 :(得分:0)

您可以使用here包使用并行处理来加速。假设您有一个名为files的文件列表,结构如下:

import ...
from joblib import Parallel, delayed

def read_the_file(file):
    ...

if __name__ == '__main__':

    n = 8 # number of processors
    Parallel(n_jobs=n)(delayed(read_the_file)(file) for file in files)

答案 1 :(得分:0)

首先,你不应该自己确定总行数或者一次读取整个文件 如果你不需要。使用类似this的循环,您已经节省了一些时间。 另外,请考虑使用readlines() http://stupidpythonideas.blogspot.de/2013/06/readlines-considered-silly.html

考虑到您正在使用XML元素,可以考虑使用一个使这更容易的库。特别是写作。

答案 2 :(得分:0)

  1. 建议:使用上下文管理器:

    with open(filename, 'r') as file:
        ...
    
  2. 建议:阅读和处理垃圾邮件(目前,您只需一步即可阅读文件,之后您将逐一浏览列表&#34;逐行扫描&#34;):

    for chunk in file.read(number_of_bytes_to_read):
        my_function(chunk)
    
  3. 当然,这样你就必须注意正确的xml标签的开始/结束。

    替代方案:寻找XML Parser包。我非常肯定有一个可以处理文件的方法,包括正确的标签处理。

相关问题