i am downloading the files inside a folder in drive, and i wanted to store them also in a local folder in the same location where my python script is, instead that saving them unorderer without a folder my current code is here:
JavaScript
x
63
63
1
import pickle
2
import os.path
3
from googleapiclient.discovery import build
4
from google_auth_oauthlib.flow import InstalledAppFlow
5
from google.auth.transport.requests import Request
6
import io
7
from googleapiclient.http import MediaIoBaseDownload
8
9
# If modifying these scopes, delete the file token.pickle.
10
SCOPES = ['https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive']
11
12
def main():
13
14
creds = None
15
# The file token.pickle stores the user's access and refresh tokens, and is
16
# created automatically when the authorization flow completes for the first
17
# time.
18
if os.path.exists('token.pickle'):
19
with open('token.pickle', 'rb') as token:
20
creds = pickle.load(token)
21
# If there are no (valid) credentials available, let the user log in.
22
if not creds or not creds.valid:
23
if creds and creds.expired and creds.refresh_token:
24
creds.refresh(Request())
25
else:
26
flow = InstalledAppFlow.from_client_secrets_file(
27
'credentials.json', SCOPES)
28
creds = flow.run_local_server(port=0)
29
# Save the credentials for the next run
30
with open('token.pickle', 'wb') as token:
31
pickle.dump(creds, token)
32
33
service = build('drive', 'v3', credentials=creds)
34
35
# Call the Drive v3 API
36
37
# supose that 213fkrjbk324fnvbknfd is the folder id
38
39
query = "'213fkrjbk324fnvbknfd' in parents"
40
41
response = service.files().list(q=query,
42
spaces='drive',
43
fields='files(id, name, parents)').execute()
44
45
for document in response['files']:
46
#file_id = service.files.list()
47
request = service.files().get_media(fileId=document['id'])
48
fh = io.FileIO('filename.extension', mode='wb')
49
downloader = MediaIoBaseDownload(fh, request)
50
done = False
51
while done is False:
52
status, done = downloader.next_chunk()
53
print(document['name'])
54
print ("Download %d%%." % int(status.progress() * 100))
55
print("-------------------------------------------------------------------------------------")
56
57
58
59
if __name__ == '__main__':
60
main()
61
62
63
when i run this code the console shows the download 100% string but i cant find the files neither on the location of my script nor on other location of the local storage.
Advertisement
Answer
The downloaded data is still stored in RAM. This copies the data to the folder where your python file is.
JavaScript
1
8
1
while done is False:
2
[ .]
3
4
# This is where it downloads the file
5
fh.seek(0)
6
with open('your_filename.pdf', 'wb') as f:
7
shutil.copyfileobj(fh, f, length=131072)
8
If you are experiencing issues, I found this answer here.