I´m triying to use Google Drive API quickstart to save all files ids with Python.
I want to save files ids in a txt document
This is my code
JavaScript
x
61
61
1
from __future__ import print_function
2
import pickle
3
import os.path
4
from googleapiclient.discovery import build
5
from google_auth_oauthlib.flow import InstalledAppFlow
6
from google.auth.transport.requests import Request
7
8
# If modifying these scopes, delete the file token.pickle.
9
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
10
11
12
13
def main():
14
"""Shows basic usage of the Drive v3 API.
15
Prints the names and ids of the first 10 files the user has access to.
16
"""
17
18
19
creds = None
20
# The file token.pickle stores the user's access and refresh tokens, and is
21
# created automatically when the authorization flow completes for the first
22
# time.
23
if os.path.exists('token.pickle'):
24
with open('token.pickle', 'rb') as token:
25
creds = pickle.load(token)
26
# If there are no (valid) credentials available, let the user log in.
27
if not creds or not creds.valid:
28
if creds and creds.expired and creds.refresh_token:
29
creds.refresh(Request())
30
else:
31
flow = InstalledAppFlow.from_client_secrets_file(
32
'credentials.json', SCOPES)
33
creds = flow.run_local_server(port=0)
34
# Save the credentials for the next run
35
with open('token.pickle', 'wb') as token:
36
pickle.dump(creds, token)
37
38
service = build('drive', 'v3', credentials=creds)
39
40
# Call the Drive v3 API
41
results = service.files().list(
42
pageSize=10, fields="nextPageToken, files(id, name)").execute()
43
items = results.get('files', [])
44
45
if not items:
46
print('No files found.')
47
else:
48
print('Files:')
49
for item in items:
50
print(u'{0} ({1})'.format(item['name'], item['id']))
51
archivo = open("Prueba.txt","a")
52
archivo.write(item['id'])
53
archivo.close()
54
55
56
57
58
if __name__ == '__main__':
59
main()
60
61
I want to save all files ids,but my program is not working properly only saves the last file id
What is happening?
Advertisement
Answer
Delete from (for items in items:) to (archivo.close())
Then copy and paste this:
JavaScript
1
6
1
for item in items:
2
print(u'{0} ({1})'.format(item['name'], item['id']))
3
archivo = open("Prueba.txt","a")
4
archivo.write(item['id'])
5
archivo.close()
6
This should work