使用python提取zip文件并保留顶级文件夹 [英] Extract zip file and keeping top folder using python
问题描述
我有像 CW1234.zip
这样的文件夹,它有各种文件夹和子文件夹,如下所示.所以,CW1234.zip
有 CW_All
文件夹,而后有 CW123
和 CW234
文件夹等等
I have folder in like CW1234.zip
and it has various folders and subfolders like below. So, CW1234.zip
has CW_All
folder which in turn has CW123
and CW234
folders and so on
CW1234.zip
CW_All
CW123
xyz.pdf
CW234
abc.doc
并提取我使用此代码:
from zipfile import ZipFile
with ZipFile(r'CW41234.zip', 'r') as zipObj:
# Extract all the contents of zip file in current directory
zipObj.extract()
唯一的问题是我得到的解压文件夹来自 CW_All 以及所有子文件夹和文件.
The only problem is the unzipped folder I get is from CW_All and all the subfolders and file.
我想要的是从 CW1234 中获取它作为一个文件夹,然后结构如下?
What I want is to get it from CW1234 as one folder and then the structure follows?
电流输出
CW_All
CW123
xyz.pdf
CW234
abc.doc
预期产出
CW1234
CW_All
CW123
xyz.pdf
CW234
abc.doc
在文档中也找不到任何东西!!
Couldn't find anything in the documentation also!!
推荐答案
使用 ZipFile.extractall()
我们可以简单地提供一个新的路径来提取档案的内容,我们可以根据档案的文件名.
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.
我有一个具有以下结构的 .zip 文件:
I have a .zip file with the following structure:
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
这篇关于使用python提取zip文件并保留顶级文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!