python - 在python中逐行读取一个大的压缩文本文件

标签 python stream zip

我正在尝试使用 zipfile 模块来读取存档中的文件。未压缩文件约为 3GB,压缩文件为 200MB。我不希望它们在内存中,因为我逐行处理压缩文件。到目前为止,我注意到使用以下代码的内存过度使用:

import zipfile
f = open(...)
z = zipfile.ZipFile(f)
for line in zipfile.open(...).readlines()
  print line

我是在 C# 中使用 SharpZipLib 完成的:

var fStream = File.OpenRead("...");
var unzipper = new ICSharpCode.SharpZipLib.Zip.ZipFile(fStream);
var dataStream =  unzipper.GetInputStream(0);

dataStream 未压缩。我似乎找不到在 Python 中做到这一点的方法。我们将不胜感激。

最佳答案

Python 文件对象提供迭代器,它将逐行读取。 file.readlines()将它们全部读取并返回一个列表 - 这意味着它需要将所有内容读入内存。更好的方法(应该总是优先于 readlines())是循环遍历对象本身,例如:

import zipfile
with zipfile.ZipFile(...) as z:
    with z.open(...) as f:
        for line in f:
            print line

注意我对 the with statement 的使用- 文件对象是上下文管理器,with 语句让我们可以轻松编写可读代码,确保在退出 block 时关闭文件(即使出现异常)。同样,在处理文件时应该始终使用它。

关于python - 在python中逐行读取一个大的压缩文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11482342/

相关文章:

linux - Unix 解压 : how to batch unzip zip files in a folder and save in subfolders?

python - 将命令行参数传递给 runpy

python - 在 gui 中更新 matplotlib 图的有效方法?

Python - 如何从现有列表中填充字典列表

c - 通过引用传递流

c# - 如何正确使用.NET2.0串口.BaseStream进行异步操作

python - 操作系统错误: [WinError 10049] How do I tackle this error?

python - 如何在 python 中将 zip 文件作为附件发送?

python - 错误处理的Python问题(尝试,除外)