Python:在内存中打开bz2压缩文件

问题描述

黑在那里,

我知道之前也曾提出过类似的要求,但我无法确定我的具体情况是什么问题。我想下载一个bz2压缩文件,对其进行解压缩并对其进行处理,而无需将任何内容写入磁盘。这就是我所拥有的:

import bz2
from io import BytesIO
import requests

url = (
    'https://opendata.dwd.de/weather/nwp/'
    'cosmo-d2/grib/00/clct/cosmo-d2_germany_'
    'regular-lat-lon_single-level_'
    '2020101400_000_CLCT.grib2.bz2'
)
file_compressed = requests.get(url).content

现在,如果我愿意

file_decompressed = bz2.BZ2File(file_compressed).read()

我明白了

ValueError: embedded null byte

我只知道这意味着什么,我不知道为什么会发生这种情况,但是我找到了一种使用BytesIO处理它的方法:

file_decompressed = bz2.BZ2File(BytesIO(file_compressed)).read()

在这里我被卡住了。如果我这样做:

with open(file_decompressed,'rb') as file:
    pass

我明白了

ValueError: embedded null byte
再次

。但这一次BytesIO的花招无法实现:

with open(BytesIO(file_decompressed),'rb') as file:
    pass


TypeError: expected str,bytes or os.PathLike object,not _io.BytesIO

(说实话:我需要一个更高级别的函数来处理该文件。但是此函数使用了open函数。因此,切换到open的变体不是一个选择。)

请注意,如果将解压缩的文件写入磁盘,则可以使用它:

with open('tmp.grib2','wb') as tmpfile:
    tmpfile.write(file_decompressed)  
with open('tmp.grib2','rb') as tmpfile:
    pass

但这就是我要摆脱的。所以我的问题是:如何在不诉诸开放功能无法处理的BytesIO的情况下处理“嵌入式空字节”?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...