python - 需要帮助改进文本处理程序(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)
解决方案
为什么要逐行附加它?像这样追加整个文件怎么样?
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())
推荐阅读
- r - 将值从 bash 文件传递到 r 文件而不回显
- ios - 在 Swift 3 中单击标签栏项目时从底部打开弹出窗口?
- c++ - 转换字符时Arduino DUE和Arduino UNO之间的区别
- c# - 自动更新检索到的记录的 ID 值
- vba - 执行 VBA 模块时访问 DB 无响应
- java - 将一个参数传递给另一个参数 - 从 Android 访问 REST 方法
- mysql - 如何使用 AND 条件从同一个表中选择多个值
- c# - 如何将图像转换为 emguCV 图像
- python - 从 Python 到 Lua 的代码转换几乎完成
- webpack - Webpack 优化模块串联:从单项救助中多引用