'Python zipfile extract files from directory inside a zip file
I need to extract some files inside a directory in a zip file.
The main problem is that I want to extract only the contents from this directory, not the directory itself with all the files inside.
I've tried by iterating on them using namelist()
or tweaking it with zipfile.Path()
, unsuccessfully.
This works but it extracts the directory with the files (like extractall()
does). Path doesn't work because raises KeyError
saying that the item doesn't exist yet it does.
for zip_file in zip_files:
with zipfile.ZipFile(os.path.join(home_path, zip_file), 'r') as zip_ref:
files = [n for n in zip_ref.namelist()]
zip_ref.extractall(os.path.join(home_path, 'dir'), members=files)
Solution 1:[1]
written from my mobile but I expect it to work:
from pathlib import Path
with ZipFile(zipfile_path, "r") as zf:
for f in zf.namelist():
if f.startswith('/'):
continue
source = zf.open(f)
target = open(target_dir / Path(f).name, "wb")
with source, target:
shutil.copyfileobj(source, target)
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 | Bobby Donchev |