我试图解压缩一个zipfile(用BZ2压缩)到一个目录。zip文件包含多个文件。
所有的例子(我已经看到了相当多的…)都展示了如何将zipfile解压缩成一个文件。
这是我目前为止写的:
def unzipBzip2(passed_targetDir, passed_zipfile):
full_zipfile = pathlib.Path(constants.APP.ROOT, constants.DOWNLOAD_FOLDER, passed_zipfile)
full_target = pathlib.Path(constants.APP.ROOT, constants.DOWNLOAD_FOLDER, passed_targetDir)
with open(file=full_zipfile, mode="rb") as zipfile, open(full_target, 'wb') as target:
decompressor = bz2.BZ2Decompressor()
for data in iter(lambda : zipfile.read(100*1024), b''):
target.write(decompressor.decompress(data))
return
错误是:
Traceback (most recent call last):
... (stack) ...
File "/Users/bert/Project/unzipBzip2.py", line 26, in unzipBzip2
with open(file=fullzipfile, mode="rb") as zipfile, open(full_target, 'wb') as target:
IsADirectoryError: [Errno 21] Is a directory: '/Users/bert/Project/data/51fba56e-c598-491a-a5e4-57373a59367a'
,"/用户/伯特/项目/数据/51 fba56e c598 - 491 a - a5e4 57373 - a59367a"确实是一个目录。它应该是这样的,因为解压缩的文件(来自BZ2 zipfile)应该写在该目录中。
为什么解压缩程序报错这是一个目录?
如果我将目标更改为文件
full_target = pathlib.Path(constants.APP.ROOT, constants.DOWNLOAD_FOLDER, passed_targetDir, 'x.x')
给出如下错误:
File "/Users/bert/Project/unzipBzip2.py", line 30, in unzipBzip2
target.write(decompressor.decompress(data))
OSError: Invalid data stream
如果您的zipfile是bz2压缩的zip文件,那么下面的代码应该可以工作。
def unzipBzip2(passed_targetDir, passed_zipfile):
full_zipfile = pathlib.Path(constants.APP.ROOT, constants.DOWNLOAD_FOLDER, passed_zipfile)
full_target = pathlib.Path(constants.APP.ROOT, constants.DOWNLOAD_FOLDER, passed_targetDir)
with open(file=full_zipfile, mode="rb") as rawf:
with bz2.BZ2File(rawf) as bz2f:
with zipfile.ZipFile(bz2f) as zipf:
zipf.extractall(full_target)
您可以尝试使用file
命令来识别归档格式。例如,你的文件是abc.unkown.bz2
$ file ./abc.unkown.bz2
./abc.unkown.bz2: bzip2 compressed data, block size = 900k
现在我们可以使用bzip2解压它,得到abc.unkown
$ bzip2 -d ./abc.unkown.bz2
然后继续解压缩abc.unkown
$ file ./abc.unkown
./abc.unkown: Zip archive data, at least v1.0 to extract
示例文件是zip
格式在bz2