gpt4 book ai didi

python - 使用 Python 下载共享的 Google Drive 文件夹

转载 作者:行者123 更新时间:2023-11-28 18:57:13 34 4
gpt4 key购买 nike

我在 google 驱动器上有一个文件夹,其中只有 .jpg 图片,我想使用文件夹的共享链接将文件夹中的所有图片下载到我的计算机。

到目前为止,我发现唯一有效的是下面的代码,但我只能让它对特定的共享文件而不是整个文件夹起作用。

from google_drive_downloader import GoogleDriveDownloader as gdd

gdd.download_file_from_google_drive(file_id='1viW3guJTZuEFcx1-ivCL2aypDNLckEMh',
dest_path='./data/mnist.zip',
unzip=True)

有没有办法修改它以使用 google 文件夹,或者有另一种方法来下载 google drive 文件夹?

最佳答案

如果您使用 Google Drive API 的 Python 快速入门教程 which you can find here ,您将能够使用 API 设置身份验证。然后,您可以通过将搜索的 MIMEType 指定为 image/jpeg 来循环浏览您的云端硬盘并仅下载 jpg 文件。

首先,您想遍历驱动器上的文件 using files: list :

# Note: folder_id can be parsed from the shared link
def listFiles(service, folder_id):
listOfFiles = []

query = f"'{folder_id}' in parents and mimeType='image/jpeg'"

# Get list of jpg files in shared folder
page_token = None
while True:
response = service.files().list(
q=query,
fields="nextPageToken, files(id, name)",
pageToken=page_token,
includeItemsFromAllDrives=True,
supportsAllDrives=True
).execute()

for file in response.get('files', []):
listOfFiles.append(file)

page_token = response.get('nextPageToken', None)
if page_token is None:
break

return listOfFiles

然后你可以使用files:get_media()方法下载它们:

import io
from googleapiclient.http import MediaIoBaseDownload

def downloadFiles(service, listOfFiles):
# Download all jpegs
for fileID in listOfFiles:
request = service.files().get_media(fileId=fileID['id'])
fh = io.FileIO(fileID['name'], 'wb')
downloader = MediaIoBaseDownload(fh, request)

done = False
while done is False:
status, done = downloader.next_chunk()
print("Downloading..." + str(fileID['name']))

您可以使用 listFiles() 中指定的 q 参数进一步优化搜索 here .

关于python - 使用 Python 下载共享的 Google Drive 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56857900/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com