'Get root folder of extracted Zipfile
Using Zipfile in Python 3.6, I am able to successfully extract a zip using:
with zipfile.ZipFile(my_zip,"r") as zip_ref:
zip_ref.extractall('./download')
The zip will always contain one top level folder:
- with a unique ID filename that is different to the original ZIP filename
- Ends with .gdb
- Has other folders and files within it.
I need to return the name of the top level extracted folder, highlighted above.
zip_ref.namelist() and zip_ref.filelist = Returns all the files under the root folder that was extracted.
I can see a way of doing this using replace on one of the paths of the files in the underlying folder, but feels like the wrong approach.
Can someone point me in the right direction please?
Solution 1:[1]
I'd use zipfile.Path
for this. Use is similar to pathlib.Path
.
Unlike zip files, these path objects can represent directories. If you're confident there is exactly one top level directory that should be created by extractall
, you could do this:
with zipfile.ZipFile(my_zip,"r") as zip_ref:
relativepath, = zipfile.Path(zip_ref).iterdir()
print(relativepath.name) # Should print the name of the folder, without prefix or slashes.
# If you want the location on the filesystem it can be found, don't forget to join it to the directory, like with pathlib.Path('./download') / relativepath.name
zip_ref.extractall('./download')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jasmijn |