首页 > 编程问答 >尝试通过Python访问.zip文件中的.gz文件

尝试通过Python访问.zip文件中的.gz文件

时间:2024-07-31 10:30:23浏览次数:7  
标签:python zip compression gzip python-zipfile

我有一个包含大量 .gz 文件的 .zip 文件,我需要对其进行处理。我想打开.zip,我可以通过以下代码轻松完成:

zf = zipfile.ZipFile("file.zip", "r")
for gzfile in zf.filelist:
    with gzip.GzipFile(fileobj=zf.open(gzfile.filename, "r"), mode="r") as f:
        df = pd.read_csv(f, compression="gzip", sep=";")

但是,这会导致 NotImplementedError: That compression method is not supported ,这是由 zf.open(gzfile) 引起的。与此相关的现有 StackOverflow 票证并未解决此问题。


你遇到的错误是因为你试图在 gzip.GzipFile 中解压一个已经由 zipfile.ZipFile 打开的对象。 zipfile.ZipFile.open() 方法返回一个类似文件的对象,该对象代表压缩存档 的文件,但它本身并没有被解压缩。

为了解决这个问题,你需要首先从zip存档中 提取 .gz 文件,然后解压它。

以下是你可以如何做到的:

import zipfile
import gzip
import pandas as pd
import io

# 打开 zip 文件
with zipfile.ZipFile("file.zip", "r") as zf:
    # 遍历 zip 文件中的每个 .gz 文件
    for gzfile in zf.filelist:
        # 提取 .gz 文件到内存中
        with zf.open(gzfile.filename) as gzdata:
            # 使用 io.BytesIO 将字节数据包装成类文件对象
            with io.BytesIO(gzdata.read()) as gzfile:
                # 打开 .gz 文件进行读取
                with gzip.GzipFile(fileobj=gzfile, mode="rb") as f:
                    # 使用 pandas 读取 csv 数据
                    df = pd.read_csv(f, compression="gzip", sep=";")
                    # 对 DataFrame 进行处理
                    print(df.head())

这段代码执行以下操作:

  1. 打开 zip 文件: 使用 zipfile.ZipFile 打开 zip 文件。
  2. 遍历 .gz 文件: 迭代 zip 存档中的所有文件。
  3. 提取 .gz 文件: 使用 zf.open() 读取 .gz 文件的内容,并将其存储在内存中的 io.BytesIO 对象中。
  4. 解压 .gz 文件: 使用 gzip.GzipFile 并将 io.BytesIO 对象作为 fileobj 传递给它来打开 .gz 文件。
  5. 读取 CSV 数据: 使用 pd.read_csv 读取解压后的 CSV 数据。

注意: 将整个 .gz 文件提取到内存中可能会消耗大量内存,特别是如果文件很大的话。如果你的 .zip 文件非常大,你可能需要考虑将 .gz 文件提取到磁盘上的临时文件中,然后再进行处理。

标签:python,zip,compression,gzip,python-zipfile
From: 78812532

相关文章

  • python导入包报错ImportError: cannot import name ‘Protocol‘
    python32.pyTraceback(mostrecentcalllast):File"2.py",line5,in<module>importptwt#use"fromsrcimportptwt"foraclonedtherepoFile"……lib/python3.6/site-packages/ptwt/_util.py",line2......
  • Python - Creating your own Iterator
    Inourfirstexample,wewillcreateiterableobjects,which,wheniteratedover,willgiveoutcubesofnumbers,andtheseobjectswillsupportmultipleiterations.classCubes:def__init__(self,start,stop):self.start=startsel......
  • 三种语言实现前缀和(C++/Python/Java)
    题目输入一个长度为n的整数序列。接下来再输入m个询问,每个询问输入一对l,r对于每个询问,输出原序列中从第l个数到第r个数的和。输入格式第一行包含两个整数n和m。第二行包含n个整数,表示整数数列。接下来m行,每行包含两个整数l和r,表示一个询问的区间范围。......
  • Python - 旨在通过命令提示符执行数据清理,但代码似乎无法运行
    我从一位同事那里收到了这段代码,我打算用它来处理100csv文件以提取有关粒子的值。代码如下所示:importsysimportcsv#Usage#skdata_decode.py[inputfile1][inputfile2]...#(Itispossibletousefiledcardtospecifyinputfiles.)##l......
  • 如何在 python 终端中的 x,y 位置上书写(基于文本)
    我想在python(基于文本)的终端中的定义位置(x,y)上写入字符。假设,我有一个大小为25x80的终端,并且想要在位置(2,20)上写入字符。我可以在Python中执行此操作吗?现在,我使用25x80数组,并写入该数组。为了在屏幕上显示,我清除屏幕并将该数组的全部内容写入屏幕,但这效......
  • Python - Composition
     classEngine:def__init__(self,power):self.power=powerdefstart(self):self.draw_current()self.spin()self.ignite()defdraw_current(self):print('Drawingcurrent')defspin(sel......
  • Python - Iterator vs Iterable
    Therearemanybuilt-infunctionsandmethodsthatreturniterablesanditerators.Hereareafewexamples:range()returnsaniterabledict.keys()returnsaniterabledict.items()returnsaniterabledict.values()returnsaniterableenumerate()returns......
  • 在python中使用变量引用Panda列名称
    我正在尝试编写一个函数来简化我的代码,因此我传递了包含列名称的变量。它适用于Django应用程序,调试器不会对我的错误所在提供任何反馈,只是“内部服务器错误”。我的代码工作正常,不是作为函数编写的:df_trips['trip_time_prep_starts']=df_trips["trip_time_prep_sta......
  • 如何在 Pyqt5 Python 中实现 QTableWidget 列过滤器中的搜索栏?
    我使用pyqt5创建了一个QTableWidget,并成功地在表格小部件的每一列中添加了过滤选项,并使用堆栈溢出上可用的答案之一。过滤器按预期工作,但我想在顶部的过滤器中添加搜索栏来搜索值。在我的python脚本中,过滤器中可能有大约50多个唯一值。因此,如果有一种方法可以在过滤器......
  • Python - Abstract Base classes
    Wehaveseenthatifwehavetodefineagroupofclassesthathavesimilarfeaturesandshowcommonbehavior,wecandefineabaseclassandtheninherittheclassesfromit.Inthederivedclasses,wehavethechoicetoeitherusethebaseclassversion......