我有一个zip存档,其内部结构如下所示:
file.zip
|
--- foo/
|
--- bar/
|
--- file1.txt
|
--- dir/
|
--- file2.txt
而且我想bar
使用python3将内容提取到输出目录中,得到的内容如下所示:
output-dir/
|
--- file1.txt
|
--- dir/
|
--- file2.txt
但是,当我在两者下面运行代码时bar
,其内容正在提取到output-dir
import zipfile
archive = zipfile.ZipFile('path/to/file.zip')
for archive_item in archive.namelist():
if archive_item.startswith('bar/'):
archive.extract(archive_item, 'path/to/output-dir')
我该如何解决这个问题?谢谢!
要使用路径操纵来创建所需的输出路径,请不要使用ZipFile.extract
和使用来将文件准确地放置在所需位置ZipFile.open
,而是使用open
和。shutil.copyfileobj
archive = zipfile.ZipFile('path/to/file.zip')
PREFIX = 'bar/'
out = pathlib.Path('path/to/output-dir')
for archive_item in archive.namelist():
if archive_item.startswith(PREFIX):
# strip out the leading prefix then join to `out`, note that you
# may want to add some securing against path traversal if the zip
# file comes from an untrusted source
destpath = out.joinpath(archive_item[len(PREFIX):])
# make sure destination directory exists otherwise `open` will fail
os.makedirs(destpath.parent, exist_ok=True)
with archive.open(archive_item) as source,
open(destpath, 'wb') as dest:
shutil.copyfileobj(source, dest)
这样的事情。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句