[英]Extract zip file and keeping top folder using python
I have folder in like CW1234.zip
and it has various folders and subfolders like below.我有像
CW1234.zip
这样的文件夹,它有各种文件夹和子文件夹,如下所示。 So, CW1234.zip
has CW_All
folder which in turn has CW123
and CW234
folders and so on因此,
CW1234.zip
具有CW_All
文件夹,而 CW_All 文件夹又具有CW123
和CW234
文件夹,依此类推
CW1234.zip
CW_All
CW123
xyz.pdf
CW234
abc.doc
and to extract I use this code:并提取我使用此代码:
from zipfile import ZipFile
with ZipFile(r'CW41234.zip', 'r') as zipObj:
# Extract all the contents of zip file in current directory
zipObj.extract()
The only problem is the unzipped folder I get is from CW_All and all the subfolders and file.唯一的问题是我得到的解压缩文件夹来自 CW_All 以及所有子文件夹和文件。
What I want is to get it from CW1234 as one folder and then the structure follows?我想要的是从 CW1234 获取它作为一个文件夹,然后结构如下?
Current Output当前Output
CW_All
CW123
xyz.pdf
CW234
abc.doc
Expected Output预计 Output
CW1234
CW_All
CW123
xyz.pdf
CW234
abc.doc
Couldn't find anything in the documentation also!!在文档中也找不到任何东西!!
Using ZipFile.extractall()
we can simply provide a new path to extract the contents of the archive to, which we can base on the filename of the archive.使用
ZipFile.extractall()
我们可以简单地提供一个新的路径来提取存档的内容,我们可以基于存档的文件名。
I have a.zip file with the following structure:我有一个具有以下结构的 .zip 文件:
archive1024.zip:.
│
└───Folder_with_script
stuff.py
Here is the script to extract all of the files inside of the archive into a sub-folder:这是将存档中的所有文件提取到子文件夹中的脚本:
from zipfile import ZipFile
file = "archive1024.zip"
with ZipFile(file, "r") as zFile:
zFile.extractall(path=file.split(".")[0])
I now have a folder-structure like this:我现在有一个这样的文件夹结构:
J:.
│ archive1024.zip
│ unzip.py
│
└───archive1024
└───Folder_with_script
stuff.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.