Reputation: 384
I have google drive IDs of many files which I want to download. However the apis to download google drive files want the filename as well to save the file with that name.
Is there a way in python to get the title/name of the file from the google drive file ID in python?
If so please help to share a sample code.
Upvotes: 1
Views: 1358
Reputation: 116878
The file.get method to download a file does not require a file name it simply requires that you send it the file id.
# Call the Drive v3 API
# get the file media data
request = service.files().get_media(fileId=FILEID)
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))
What does require a name is when you want to save it to your system.
# The file has been downloaded into RAM, now save it in a file
fh.seek(0)
with open(file_name, 'wb') as f:
shutil.copyfileobj(fh, f, length=131072)
You can just do a file.get to get the metadata of the file first then you can use that when you want to save your file.
# Call the Drive v3 API
# Get file name, so we can save it as the same with the same name.
file = service.files().get(fileId=FILEID).execute()
file_name = file.get("name")
print(f'File name is: {file_name}')
Upvotes: 3