[英]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')```
您可以使用以下解決方案:
.jpg
。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.