你好全
我想下载谷歌驱动器文件直接到我的电脑上的文件夹,而不是标准的下载文件夹。此外,文件的名称应该保持不变,而不是手动设置。
我试过使用下载文件的直接下载链接下载文件,但您无法决定文件保存在计算机上的位置。
我也尝试过以下方法:
https://stackoverflow.com/a/39225272/13715296 (此方法不适用于我) https://stackoverflow.com/a/47761459/13715296 (使用此方法,我无法获得文件的原始名称)
在我的代码中,我基本上有很多这类urls:
但我可以很容易地将它们转换为这些直接下载的urls:
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)这是python快速入门页和示例代码提供的代码。
我使用google-drive按ID搜索名称,稍后可以将其添加到路径中:
path = "PATH/TO/MY/FOLDER/" + name
with open(path, 'wb') as f:
shutil.copyfileobj(fh, f)这允许我控制存储下载的路径,并保持文件名不变。当然不是我最好的代码,但它确实起作用了。
发布于 2022-01-18 09:29:03
我知道您有一个驱动器文件链接数组,您希望使用Python在本地下载它们。我假设您想下载存储在驱动器上的文件,而不是工作区文件(即Docs,Sheets…)。通过遵循驱动API Python快速启动指南,您可以很容易地做到这一点。该演练将安装所有必要的依赖项,并向您展示示例代码。然后,您只需要编辑主函数来下载文件,而不是示例操作。
要下载Python文件,只需知道其id并使用Files.get方法即可。我看到您已经知道了ids,所以您已经准备好提出请求了。要构建请求,您应该引入文件的id,并将参数alt设置为值media。如果您使用的是上面段落中的示例,那么只需使用像下面这个示例那样的id即可。如果那些导游不为你工作,请告诉我。
https://stackoverflow.com/questions/70734852
复制相似问题