我需要在zip文件的目录中提取一些文件。
主要问题是我只想从该目录中提取内容,而不要提取其中包含所有文件的目录本身。
我已经尝试过使用namelist()
或对其进行调整zipfile.Path()
,但未成功对其进行迭代。
这extractall()
可行,但是它会提取包含文件的目录(就像这样)。路径不起作用,因为KeyError
提示该项目不存在,但它确实存在。
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)
用我的手机写的,但我希望它能正常工作:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句