gpt4 book ai didi

python - 在 zip 存档中打开二进制文件作为 ZipExtFile

转载 作者:行者123 更新时间:2023-11-28 19:09:27 48 4
gpt4 key购买 nike

我正在尝试从 Zip 存档中包含的数据文件访问二进制流(通过 ZipExtFile 对象)。要从存档中增量读取文本文件对象,这将非常简单:

with ziparchive as ZipFile("myziparchive.zip", 'r'):
with txtfile as ziparchive.open("mybigtextfile.txt", 'r'):
for line in txtfile:
....

理想情况下,等效的字节流应该是这样的:

with ziparchive as ZipFile("myziparchive.zip", 'r'):
with binfile as ziparchive.open("mybigbinary.bin", 'rb'):
while notEOF
binchunk = binfile.read(MYCHUNKSIZE)
....

不幸的是,ZipFile.open 似乎不支持将二进制数据读取到 ZipExtFile 对象。来自docs :

The mode parameter, if included, must be one of the following: 'r' (the default), 'U', or 'rU'.

鉴于此约束,如何最好地直接从存档中增量读取二进制文件?由于未压缩的文件非常大,我想避免先提取它。

最佳答案

我设法解决了我在对 OP 的评论中描述的问题。为了您的目的,我在这里对其进行了调整,但我认为可能有一种方法可以只更改 chunk_str 的编码,以避免使用 ByteIO。

无论如何 - 如果有帮助,这是我的代码:

from io import BytesIO
from zipfile import ZipFile

MYCHUNKSIZE = 10

archive_file = r"test_resources\0000232514_bom.zip"
src_file = r"0000232514_bom.xls"

no_of_chunks_to_read = 10
with ZipFile(archive_file,'r') as zf:
with zf.open(src_file) as src_f:
while no_of_chunks_to_read > 0:
chunk_str = src_f.read(MYCHUNKSIZE)
chunk_stream = BytesIO(chunk_str)
chunk_bytes = chunk_stream.read()
print type(chunk_bytes), len(chunk_bytes), chunk_bytes
if len(chunk_str) < MYCHUNKSIZE:
# End of file
break
no_of_chunks_to_read -= 1

关于python - 在 zip 存档中打开二进制文件作为 ZipExtFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42233492/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com