[英]How to extract a mult-part zip file in python?
Suposse that I have some files that I downloaded from a server and they are zipped with 7zip in multiple parts, the format is something like this myfile.zip.001, myfile.zip.002, ..., myfile.zip.00n.假设我有一些从服务器下载的文件,它们被 7zip 压缩成多个部分,格式类似于 myfile.zip.001,myfile.zip.002,...,myfile.zip.00n。 Basically, I need to extract the content of it in the same folder where they are stored.
基本上,我需要将它的内容提取到存储它们的同一文件夹中。
I tried using zipfile
, patoolib
and pyunpack
without success, here is what I've done:我尝试使用
zipfile
、 patoolib
和pyunpack
但没有成功,这是我所做的:
file_path = r"C:\Users\user\Documents\myfile.zip.001" #I also tested with only .zip
extract_path = r"C:\Users\user\Documents\"
#"
import zipfile
with zipfile.ZipFile(file_path, "r") as zip_ref:
zip_ref.extractall(extract_path) # myfile.zip.001 file isn't zip file.
from pyunpack import Archive
Archive(file_path).extractall(extract_path) # File is not a zip file
import patoolib
patoolib.extract_archive(file_path, outdir=extract_path) # unknown archive format for file `myfile.zip.001'
Another way (that works, but it's very ugly) is this one:另一种方式(可行,但非常难看)是这样的:
import os
import subprocess
path_7zip = r"C:\Program Files (x86)\7-Zip\7z.exe"
cmd = [path_7zip, 'x', 'myfile.zip.001']
sp = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
But this makes the user install 7zip in his computer, which isn't a good approach of what I'm looking for.但这使得用户在他的计算机上安装 7zip,这不是我正在寻找的好方法。
So, the question is: there is at least a way to extract/unzip multi-parts files with the format x.zip.001
in python?所以,问题是:至少有一种方法可以在 python 中提取/解压缩格式为
x.zip.001
的多部分文件吗?
You seem to be on the right track with zipfile
, but you most likely have to concatenate the zip file before using extractall
.您似乎在
zipfile
的正确轨道上,但您很可能必须在使用extractall
之前连接 zip 文件。
import os
zip_prefix = "myfile.zip."
# N number of parts
import glob
parts = glob.glob(zip_prefix + '*')
n = len(parts)
# Concatenate
with open("myfile.zip", "wb") as outfile:
for i in range(1, n+1):
filename = zip_prefix + str(i).zfill(3)
with open(filename, "rb") as infile:
outfile.write(infile.read())
# Extract
import zipfile
with zipfile.ZipFile(file_path, "r") as zip_ref:
zip_ref.extractall(extract_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.