You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码性能优化求助:多文件读取处理慢于Perl

Python大文件批量处理优化方案

针对你处理30个15万行文件耗时过久的问题,给你几个直接有效的优化方向:

  • 提升文件读取效率
    避免默认小缓冲区读取,打开文件时指定大缓冲区(比如buffering=1024*1024,即1MB缓冲区),减少IO调用次数:

    with open(file_path, 'r', buffering=1024*1024) as f:
        for line in f:
            # 处理逻辑
    

    如果是结构化文本(如CSV),直接用csv.reader或pandas.read_csv,这类库的底层是C实现,比纯Python逐行处理快得多。

  • 并行处理多文件
    文件读取属于IO密集型任务,用多线程/进程并行处理多个文件,避免单线程等待IO的空耗。比如用concurrent.futures.ThreadPoolExecutor:

    from concurrent.futures import ThreadPoolExecutor
    from collections import defaultdict
    
    def handle_single_file(file_path):
        stats = defaultdict(int)
        with open(file_path, 'r', buffering=1024*1024) as f:
            for line in f:
                # 示例:按逗号拆分取第一个字段统计
                key = line.strip().split(',')[0]
                stats[key] += 1
        return stats
    
    def main(file_list):
        total_stats = defaultdict(int)
        with ThreadPoolExecutor(max_workers=8) as executor:
            # 并行处理所有文件,收集结果后汇总
            for res in executor.map(handle_single_file, file_list):
                for k, v in res.items():
                    total_stats[k] += v
        # 写入最终结果
        with open('output.txt', 'w') as f:
            for k, v in total_stats.items():
                f.write(f"{k}: {v}\n")
    
  • 优化内存与数据结构
    用collections.defaultdict或collections.Counter代替普通字典做统计,这类内置数据结构的操作效率更高;避免在循环中频繁拼接字符串,改用str.join()或io.StringIO缓存输出内容,减少内存碎片。

  • 减少循环内的重复操作
    把循环内的重复计算、方法调用提到循环外,比如:

    # 低效写法:每次循环都重复调用strip和split
    for line in f:
        key = line.strip().split(',')[0]
    # 优化:如果行格式固定,简化操作减少方法调用
    for line in f:
        comma_pos = line.index(',')
        key = line[:comma_pos].rstrip('\n')
    
  • 用C扩展库加速
    如果涉及复杂文本匹配,用regex模块替代标准re;数值型统计用numpy/pandas,这类库的核心逻辑由C实现,性能远超纯Python。


内容的提问来源于stack exchange,提问作者이해찬

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:55:08