import os
import io
import zipfile
from google.oauth2 import service_account
from googleapiclient.errors import HttpError
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
def list_and_download_zip_files(folder_id):
SCOPES = ['https://www.googleapis.com/auth/drive']
creds = None
creds = service_account.Credentials.from_authorized_user_file('path/to/credentials.json', SCOPES)
try:
service = build('drive', 'v3', credentials=creds)
results = service.files().list(q=f"'{folder_id}' in parents", fields="nextPageToken, files(id, name, mimeType)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
if item["mimeType"] == "application/zip":
print('{0} ({1})'.format(item['name'], item['id']))
request = service.files().get_media(fileId=item['id'])
file = io.BytesIO()
downloader = MediaIoBaseDownload(file, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Downloading %d%%." % int(status.progress() * 100))
file.seek(0)
with zipfile.ZipFile(file, 'r') as z:
z.extractall("path/to/save/zip/contents")
else:
print('{0} ({1}) - Not a zip file'.format(item['name'], item['id']))
except HttpError as error:
print(f'An error occurred: {error}')
items = None
return items
folder_id = 'your_folder_id' # Replace with your Google Drive folder ID
list_and_download_zip_files(folder_id)
Make sure to replace path/to/credentials.json with the path to your credentials file and your_folder_id with the ID of the Google Drive folder. Additionally, you can replace path/to/save/zip/contents with the destination path where you want to save the zip file contents.