如何在python中更快地操作大型文件?

如何在python中更快地操作大型文件?,python,bigdata,Python,Bigdata,我必须循环使用30GB的文件(其中有30个),500mb大约需要15分钟。 知道我正在逐行循环,如何优化性能 蟒蛇 import json import os def file_subreddit_comments(rfname,wfname): with open(rfname, 'r', encoding="utf8") as rf: with open(wfname, 'w', encoding="utf-8") as wf: for i,

我必须循环使用30GB的文件(其中有30个),500mb大约需要15分钟。 知道我正在逐行循环,如何优化性能

蟒蛇

import json
import os

def file_subreddit_comments(rfname,wfname):
    with open(rfname, 'r', encoding="utf8") as rf:
        with open(wfname, 'w', encoding="utf-8") as wf:
            for i, l in enumerate(rf):
                d = json.loads(l)
                link_id = d["link_id"]
                for lsi in list_submission_id:
                    constructed_link_id = "t3_" + lsi
                    if link_id == constructed_link_id:
                        wf.write(l)                    

defaultFilePath = r'D:\Users\Jonathan\Desktop\Reddit Data\Run Comments\\'
directory = os.fsencode(defaultFilePath)

list_submission_id = []
submission_id_file = r'D:\Users\Jonathan\Desktop\Reddit Data\Manipulated Data-09-03-19-Final\UniqueIDSubmissionsList-09-03-2019.txt'
with open(submission_id_file, "r", encoding="utf8") as sif:
    for i, l in enumerate(sif):
        list_submission_id.append(l.rstrip())

for file in os.listdir(directory):
     filename = os.fsdecode(file)
     comment_path_read = defaultFilePath + filename
     comment_path_save = defaultFilePath + filename + "_ext_com.txt"
     file_subreddit_comments(comment_path_read,comment_path_save)     
     print(filename)

submission\u id\u文件
是一个包含大约1000个关键字的列表,它需要验证每个关键字的
constructured\u link\u id
的值是否在列表中。

多线程和多处理可能是上面Thom提出的解决方案。至少它缩短了我执行任务的时间。12核=同时操作12个文件。

如果在旋转盘片硬盘上执行此操作,可能会出现寻道时间问题。尝试将所有数据写入内存对象,然后在结束时立即将其转储到文件中

我不能100%肯定这就是问题所在,这只是一个理论。不过很容易尝试

编辑:刚刚发现另一个巨大的加速

改为设置列表\提交\ id

list_submission_id = set()
list_submission_id.add("t3_" + l.rstrip())
然后使用以下工具检查成员资格:

link_id = d["link_id"]
if link_id in list_submission_id :
    wf.write(l)      

与我的其他建议不同,这肯定会大大加快速度。

您可能想看看python中的并行处理,以便能够同时解析多个文件并利用所有CPU。我能够完成上述代码的多处理版本。它一次处理12个文件。谢谢你,这肯定会有很大帮助!如果需要这些子批次的交互,则使用多线程;如果你不需要多处理。