Skip to main content
 首页 » 编程设计

python之使用 Python 加速并行读取大文件

2024年12月31日10zlslch

我需要处理两个大文件(> 10 亿行),并根据一个文件中特定行的信息将每个文件拆分为多个小文件。 这些文件以blocks(我们称测序reads)记录高通量测序数据,而每个read包含4行,(name、序列、n、质量)。 读取记录在两个文件中的顺序相同。

待办事项

根据file2.fq中的id字段拆分file1.fq,

这两个文件看起来像这样:

$ head -n 4 file1.fq 
@name1_1 
ACTGAAGCGCTACGTCAT 
+ 
A#AAFJJJJJJJJFJFFF 
 
$ head -n 4 file2.fq 
@name1_2 
TCTCCACCAACAACAGTG 
+ 
FJJFJJJJJJJJJJJAJJ 

我编写了以下 python 函数来完成这项工作:

def p7_bc_demx_pe(fn1, fn2, id_dict): 
    """Demultiplex PE reads, by p7 index and barcode""" 
    # prepare writers for each small files 
    fn_writer = {} 
    for i in id_dict: 
        fn_writer[i] = [open(id_dict[i] + '.1.fq', 'wt'), 
            open(id_dict[i] + '.2.fq', 'wt')] 
 
    # go through each record in two files 
    with open(fn1, 'rt') as f1, open(fn2, 'rt') as f2: 
        while True: 
            try: 
                s1 = [next(f1), next(f1), next(f1), next(f1)] 
                s2 = [next(f2), next(f2), next(f2), next(f2)] 
                tag = func(s2) # a function to classify the record 
                fn_writer[tag][0].write(''.join(s1)) 
                fn_writer[tag][1].write(''.join(s2)) 
            except StopIteration: 
                break 
    # close writers 
    for tag in p7_bc_writer:  
        fn_writer[tag][0].close() # close writers 
        fn_writer[tag][1].close() # close writers 

问题

有什么办法可以加快这个过程吗? (以上功能太慢了)

如何将大文件拆分成具有特定行(如 f.seek())的 block ,并使用多个内核并行运行该过程?

EDIT-1

每个文件总共有 5 亿次读取(大小约为 180 GB)。瓶颈是读写文件。以下是我目前的解决方案(有效,但绝对不是最好的)

我首先使用 shell 命令将大文件拆分为较小的文件:split -l(大约需要 3 小时)。

然后,将函数并行应用于 8 个小文件(大约需要 1 小时)

最后,合并结果(大约需要 2 小时)

not trying PySpark yet, thanks @John H

请您参考如下方法:

研究 Spark。您可以将文件分布在一个集群中,以加快处理速度。有一个 python API:pyspark。

https://spark.apache.org/docs/0.9.0/python-programming-guide.html

这还为您提供了实际执行 Java 代码的优势,它不受 GIL 的影响并允许真正的多线程。