簡體   English   中英

如何在 Python 中讀取壓縮文件夾內文件夾中的文件

[英]How to read files in a folder within a zipped folder in Python

我有一個壓縮文件夾,其中包含一個子文件夾,該子文件夾中有大約 60000 多個圖像。 我想知道是否有辦法讀取子文件夾中的所有圖像而不提取它(因為圖像文件夾的大小約為 100GB)。

我正在考慮在 python 中使用 zipfile 包。但是我將無法在模塊中使用 open 函數,因為我不知道如何遍歷整個子文件夾。 如果您能向我提供有關如何執行此操作的任何意見,那就太好了

with zipfile.ZipFile("/home/diliptmonson/abc.zip","r") as zip_ref:
    train_images=zip_ref.open('train/86760c00-21bc-11ea-a13a-137349068a90.jpg')```

您可以使用以下解決方案:

  • 打開 zip 文件,並按照此處所述迭代內容。
  • 驗證文件擴展名是.jpg
  • 從 zip 讀取特定元素(文件夾內的文件)的圖像二進制數據。
  • 使用cv2.imdecode將二進制數據解碼為圖像。

這是代碼:

from zipfile import ZipFile
import numpy as np
import cv2
import os

# https://thispointer.com/python-how-to-get-the-list-of-all-files-in-a-zip-archive/
with ZipFile("abc.zip", "r") as zip_ref:
   # Get list of files names in zip
   list_of_files = zip_ref.namelist()

   # Iterate over the list of file names in given list & print them
   for elem in list_of_files:
       #print(elem)
       ext = os.path.splitext(elem)[-1]  # Get extension of elem

       if ext == ".jpg":
           # Read data in case extension is ".jpg"
           in_bytes = zip_ref.read(elem)

           # Decode bytes to image.
           img = cv2.imdecode(np.fromstring(in_bytes, np.uint8), cv2.IMREAD_COLOR)

           # Show image for testing
           cv2.imshow('img', img)
           cv2.waitKey(1000)

cv2.destroyAllWindows()

使用 for 循環:

# namelist lists all files
for file in zip_ref.namelist():
   opened_file = zip_ref.open(file)
   # do stuff with your file 

暫無
暫無

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

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