[英]Download Google Drive files to a specific location using Python
大家好,
我想將 google-drive 文件直接下載到我電腦上的文件夾而不是標准下載文件夾。 此外,文件的名稱應保持不變,而不是手動設置。
我曾嘗試使用下載文件的直接下載鏈接下載文件,但您無法決定文件在計算機上的保存位置。
我也試過這些方法:
https://stackoverflow.com/a/39225272/13715296 (這個方法對我不起作用)
在我的代碼中,我基本上有很多這些類型的網址:
https://drive.google.com/file/d/xxxxxxxxxxxxxxxxxxx/view?usp=drive_web
但我可以輕松地將它們轉換為這些直接下載網址:
https://drive.google.com/u/0/uc?id=xxxxxxxxxxxxxxxxxxx&export=download
我只是還沒有找到一種方法,如何使用 python 將文件下載到特定文件夾,同時保持文件的原始名稱相同。
解決方案
使用@Jacques-GuzelHeron 建議的方法,我現在有了以下代碼:
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('drive', 'v3', credentials=creds)
for id_url in list_urls:
file_id = id_url
results = service.files().get(fileId=file_id).execute()
name = results['name']
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))
fh.seek(0)
# Write the received data to the file
path = "PATH/TO/MY/FOLDER/" + name
with open(path, 'wb') as f:
shutil.copyfileobj(fh, f)
我使用 google-drive-api 按 ID 搜索名稱,稍后我可以將其添加回路徑中:
path = "PATH/TO/MY/FOLDER/" + name
with open(path, 'wb') as f:
shutil.copyfileobj(fh, f)
這使我可以控制存儲下載的路徑並保持文件名不變。 絕對不是我最好的代碼,但它確實完成了工作。
我了解到您有一系列 Drive 文件鏈接,並且您想使用 Python 在本地下載它們。 我假設您要下載存儲在 Drive 上的文件,而不是 Workspace 文件(即文檔、表格……)。 您可以按照Drive API Python 快速入門指南輕松完成此操作。 該演練將安裝所有必要的依賴項並向您展示示例代碼。 然后,您只需編輯主 function 即可下載文件,而不是示例操作。
要下載 Python 文件,您只需要知道它的 id 並使用Files.get
方法。 我看到您已經知道 ID,因此您已准備好提出請求。 要構建請求,您應該引入文件的 id 並將參數alt
設置為值media
。 如果您使用的是上一段中的示例,則只需使用 id 即可,如 this example 。 如果這些指南對您不起作用,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.