[英]Download Shared Google Drive Folder with Python
我在谷歌驅動器上有一個只有 .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 Drive API 的 Python 快速入門教程,您將能夠使用 API 設置您的身份驗證。 然后,您可以循環瀏覽您的驅動器,並通過將搜索的 MIMEType 指定為image/jpeg
來僅下載jpg
文件。
首先,您要使用files: list
遍歷驅動器上的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
參數進一步細化您的搜索。
您可以使用gdrive工具。 基本上它是一個從命令行訪問谷歌驅動器帳戶的工具。 按照以下示例為 Linux 機器進行設置:
gdrive
。 現在通過執行命令chmod +x gdrive
來更改文件的權限。./gdrive about
,你會得到一個 URL,要求你輸入驗證碼。 按照提示中的說明復制鏈接並轉到瀏覽器上的 URL,然后登錄您的 Google Drive 帳戶並授予權限。 最后你會得到一些驗證碼。 復制它。現在一旦完成上述過程,您就可以使用下面提到的命令瀏覽驅動器上的文件。
./gdrive list # List all files' information in your account
./gdrive list -q "name contains 'University'" # serch files by name
./gdrive download fileID # Download some file. You can find the fileID from the 'gdrive list' result.
./gdrive upload filename # Upload a local file to your google drive account.
./gdrive mkdir # Create new folder
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.