首页 > 解决方案 > 需要帮助改进文本处理程序(Python 3)

问题描述

我编写了一个 python 程序来循环遍历 X 文件列表,打开每个文件,逐行读取,然后写入(附加)到输出文件。由于这些文件每个都有几个 GB,因此需要很长时间..

我正在寻找提高这个程序性能的建议。我没有正式的 CS 培训,所以我很可能错过了这个问题的“明显解决方案”;我已经做了一些研究,但同样,我有限的知识(和其他更高优先级的任务)限制了我实现此类的能力......这也是我关于堆栈溢出的第一篇文章..提前谢谢你。

for name in PR_files:
    with open(PR_path + name, 'r') as f:
        line = f.readline()
        while line:
            with open(PR_out_path, 'a') as g:
                g.write(line + '\n')
                line = f.readline()
    f.close()

上面的程序可以工作,但在输出文本文件的每一行之间会有一个空行;这是因为下一个文件的第一行从前一个文件的最后一行开始(我对这个问题的解决方案是在写入输出文件的每一行中添加 '\n' .. 因此我写了另一个块删除输出文件中的所有空行(是的,效率很低,可能是更好的方法)

# this removes all blank lines from out put file
with open(PR_out_path) as this, open(PR_out_path_fix, 'w') as that:
    for line in this:
        if not line.strip():
            continue
        that.write(line)

标签: pythoniotext-processing

解决方案


为什么要逐行附加它?像这样追加整个文件怎么样?

with open(PR_out_path, 'a') as g:
    for name in PR_files:
        with open(PR_path + name, 'r') as f:
            g.write(f.read())

推荐阅读