首页 > 解决方案 > 在 python 中打开大的 gzip 文件(~1gb)

问题描述

我是python的初学者,正在尝试学习python。我已经编写了几行代码来打开一个大的 gzip 文件(大小约为 1gb)并想要提取一些内容,但是我收到了与内存相关的错误。有人可以指导我如何打开内存有限的 gzip。我已经放置了一部分引发错误的代码。

import os
import gzip

with gzip.open("test.gz","rb") as peak:
     for line in peak:
         file_content = line.read().decode("utf-8")             
         print(file_content)

错误:文件“/software/anaconda3/lib/python3.7/gzip.py”,第 276 行,读取返回 self._buffer.read(size)

标签: python-3.x

解决方案


我正在尝试重现您的问题,但我无法做到。使用fallocate我创建一个大文件,然后 gzip 它,但在 Python 中没有出现错误

$ fallocate -l 2G tempfile.img
$ gzip tempfile.img
$ ipython
>>> import gzip
>>> with gzip.open('tempfile.img.gz', 'rb') as fIn:
>>>    content = fIn.read()

如果遇到异常,它应该有一些类似OSError或更具体的名称。我的猜测是你有一个 32 位的 Python 安装,它会在千兆字节范围内施加内存限制。这个SO 线程介绍了一种检查您运行的是 32 位还是 64 位的方法。

如果您发布异常的名称或可重现的示例,那么我可以更新此答案。


推荐阅读