问题
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
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.
What I want is to get it from CW1234 as one folder and then the structure follows?
Current Output
CW_All
CW123
xyz.pdf
CW234
abc.doc
Expected Output
CW1234
CW_All
CW123
xyz.pdf
CW234
abc.doc
Couldn't find anything in the documentation also!!
回答1:
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.
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
来源:https://stackoverflow.com/questions/63076690/extract-zip-file-and-keeping-top-folder-using-python