Hello all,
I would like to download google-drive files directly to a folder on my pc rather than the standard download folder. Also, the name of the file should stay the same and not manually set.
I have tried downloading the files using the direct download link which downloads the file but you cannot decide where the file saves on your computer.
I also have tried these methods:
https://stackoverflow.com/a/39225272/13715296 (This method did not work for me)
https://stackoverflow.com/a/47761459/13715296 (With this method I could not have the original name of the file)
In my code I basically have a lot of these type of urls:
https://drive.google.com/file/d/xxxxxxxxxxxxxxxxxxx/view?usp=drive_web
But I can easily convert them to these direct download urls:
https://drive.google.com/u/0/uc?id=xxxxxxxxxxxxxxxxxxx&export=download
I just have not found a method on how to download the files using python to a specific folder while keeping the original name of the file the same.
SOLUTION
With the method suggested by @Jacques-GuzelHeron I have now this code:
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)
This is the code provided from the python quickstart page and the example code.
I used the google-drive-api to search for the name by ID, which I could later add back into the path:
path = "PATH/TO/MY/FOLDER/" + name
with open(path, 'wb') as f:
shutil.copyfileobj(fh, f)
This allowed me to control the path where I stored the download and keep the name of the file unchanged. Definitely not my best code, but it did do the job.