簡體   English   中英

從 Python3 中的 zip 存檔中提取特定文件夾的內容

[英]Extract the content of a specific folder from a zip archive in Python3

我有一個 zip 存檔,其內部結構如下所示:

file.zip
  |
   --- foo/
  |
   --- bar/
        |
         --- file1.txt
        |
         --- dir/
              |
               --- file2.txt

我想使用 python3 將bar的內容提取到輸出目錄,得到如下所示的內容:

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.openopenshutil.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)

類似的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM