如何优化读取和比较多个文件之间的行?

2024-05-23 23:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

怎样才能使读取文件更有效率?使用这个

    with open(fname, 'r') as myf:
        for myline in myf:

或者

    for glob.glob('*.txt'):

我执行了cprofile统计,这是我得到的一些排序行:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      4/1    0.000    0.000 1895.428 1895.428 {built-in method builtins.exec}
        1  157.201  157.201 1895.428 1895.428 runmyfiles.py:2(<module>)
        5 1365.371  273.074 1554.015  310.803 runmyfiles.py:9(readFile)
    52727  184.205    0.003  184.205    0.003 {method 'write' of '_io.TextIOWrapper' objects}
   194515    0.300    0.000   74.091    0.000 /usr/lib/python3.6/re.py:214(findall)
   194515   72.479    0.000   72.479    0.000 {method 'findall' of '_sre.SRE_Pattern' objects}

我知道我应该优化文件读取过程,但不知道如何进行。我可能需要一次打开所有文件,并将每个文件中的每一行与其他文件中的类似行进行比较,然后为包含bb的最大值的行写入输出。考虑到生成的统计数据,这符合逻辑吗?你知道吗


Tags: 文件ofinpyforobjectswithopen