逐行阅读大型文本文件仍然占用我的全部内存

2024-05-14 14:02:12 发布

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

我正在编写一个简单的程序,它应该读取一个大文件(准确地说是263.5gb),每行(link here)都有JSON。我做了一些研究,发现最好的方法是逐行阅读。我的看起来像这样(full code here):

with open(dumpLocation, "r") as f:
for line in f:

    # Read line, convert to dictionary and assign it to 'c'
    c = json.loads(f.readline())

    for n in files:
        if n.lower() in c["title"].lower():

            try:
                # Collect data
                timestamp = str(c["retrieved_on"])
                sr_id = c["subreddit_id"]
                score = str(c["score"])
                ups = str(c["ups"])
                downs = str(c["downs"])
                title = ('"' + c["title"] + '"')

                # Append data to file
                files[n].write(timestamp + ","
                               + sr_id + ","
                               + score + ","
                               + ups + ","
                               + downs + ","
                               + title + ","
                               + "\n")
                found += 1
            except:
                numberOfErrors += 1
                errors[comments] = sys.exc_info()[0]

        comments += 1

        # Updates user
        print("Comments scanned: " + str(comments) + "\nFound: " + str(found) + "\n")

现在我可以让它运行了,它在崩溃前运行了一个小时(大约130万行)。我注意到在进程中,内存使用量在缓慢增长,在崩溃前达到2gb左右。你知道吗

我需要整理大约2亿行,如果找到了特定的单词,我也在写文件(搜索了5行,在崩溃前找到了337行)。有没有更好的办法?我的电脑通常只有2gb左右的内存


Tags: 文件toinidforheretitleline
2条回答

我找到了内存泄漏的地方。在这一行中,我在每行之后打印到控制台:

 print("Comments scanned: " + str(comments) + "\nFound: " + str(found) + "\n")

打印2亿次,你的计算机一定会用尽内存,试图一次将所有内容保存在控制台中。删除它,它工作得很好:)

您的内存泄漏:

except:
    numberOfErrors += 1
    errors[comments] = sys.exc_info()[0]

对于大量的输入行,错误的数量也可能是巨大的,特别是如果您的算法中有一些错误的话。你知道吗

普通的except是有害的,因为它隐藏了代码中的所有错误,甚至语法错误。您应该只处理您期望在实际数据上发生的特定异常类型,并使try except block尽可能窄。你知道吗

相关问题 更多 >

    热门问题