简体   繁体   中英

How to find a particular file id of google drive?

In this code, I am finding a particular folder Id against its name. But I want to find a particular file id against its name. How to do it?

def findId(self, filename):
    page_token = None
    while True:
        response = self.service.files().list(q="name = '"+ filename +"' and mimeType = 'application/vnd.google-apps.folder'",
                                                  spaces='drive',
                                                  fields='nextPageToken, files(id, name)',
                                                  pageToken=page_token).execute()
        for file in response.get('files', []):
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

Lets look at how the q parameter for the file.list method actually works. This opitno lets you search on a lot of things, name is just one of them.

The first thing to remember is everything in Google drive is a file and it has a fileid. So your current search is searching for files with the name of filename and the internal google drive mime type of folder.

name = '"+ filename +"' and mimeType = 'application/vnd.google-apps.folder'",

You could then switch this to just search after name which would then return all the files with any mimetype that match that name.

name = '"+ filename +"'"

You will then get a list back of all the files that match that name, the problem then being if you have more the one file on your drive account matching that name.

def findId(self, filename):
    page_token = None
    while True:
        response = self.service.files().list(q="name = '"+ filename +"'",
                                                  spaces='drive',
                                                  fields='nextPageToken, files(id, name)',
                                                  pageToken=page_token).execute()
        for file in response.get('files', []):
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

There is some documentation you might find interesting that goes into detail which options you can send with Q parameter search files I also have a video which explains it Google drive API V3: Beginners to listing files and searching files you may find the explantation helpful, the code itself is in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM