尝试加载5GB文本文件时出现Python MemoryError [英] Python MemoryError when trying to load 5GB text file

查看:87
本文介绍了尝试加载5GB文本文件时出现Python MemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取以文本格式存储在5GB文件中的数据.当我尝试使用此代码读取文件的内容时:

I want to read data stored in text format in a 5GB file. when I try to read the content of file using this code:

file = open('../data/entries_en.txt', 'r')
data = file.readlines()

发生错误:数据= file.readlines()内存错误我的笔记本电脑有8GB内存,当我要运行该程序时至少有4GB可用空间.但是当我监视系统性能时,当python使用约1.5GB内存时,就会发生此错误.
我正在使用python 2.7,但是如果有问题,请告诉我2.x和3.x的解决方案我应该怎么做才能读取此文件?

an error occurred: data = file.readlines() MemoryError My laptop has 8GB memory and at least 4GB is empty when I want to run the program. but when I monitor the system performance, when python uses about 1.5GB of memory, this error happens.
I'm using python 2.7, but if it matters please tell me solution for 2.x and 3.x What should I do to read this file?

推荐答案

处理大型文件的最佳方法是-

The best way for you to handle large files would be -

with open('../file.txt', 'r') as f:
    for line in f:
        # do stuff

readlines()将出错,因为您试图将太大的文件直接加载到内存中.处理完文件后,上面的代码将自动关闭文件.

readlines() would error because you are trying to load too large a file directly into the memory. The above code will automatically close your file once you are done processing on it.

这篇关于尝试加载5GB文本文件时出现Python MemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆