Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of files in a google drive folder with python

I've got the exact same question as the one asked on this post: List files and folders in a google drive folder I don't figure out in the google drive rest api documentation how to get a list of files in a folder of google drive

like image 662
javi padilla Avatar asked Sep 11 '25 15:09

javi padilla


1 Answers

Here's a hacky-yet-successful solution. This actually gets all the files from a particular Google Drive folder (in this case, a folder called "thumbnails"). I needed to get (not just list) all the files from a particular folder and perform image adjustments on them, so I used this code:

`# First, get the folder ID by querying by mimeType and name
folderId = drive.files().list(q = "mimeType = 'application/vnd.google-apps.folder' and name = 'thumbnails'", pageSize=10, fields="nextPageToken, files(id, name)").execute()
# this gives us a list of all folders with that name
folderIdResult = folderId.get('files', [])
# however, we know there is only 1 folder with that name, so we just get the id of the 1st item in the list
id = folderIdResult[0].get('id')

# Now, using the folder ID gotten above, we get all the files from
# that particular folder
results = drive.files().list(q = "'" + id + "' in parents", pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

# Now we can loop through each file in that folder, and do whatever (in this case, download them and open them as images in OpenCV)
for f in range(0, len(items)):
    fId = items[f].get('id')
    fileRequest = drive.files().get_media(fileId=fId)
            fh = io.BytesIO()
            downloader = MediaIoBaseDownload(fh, fileRequest)
            done = False
            while done is False:
                status, done = downloader.next_chunk()
    fh.seek(0)
    fhContents = fh.read()
    
    baseImage = cv2.imdecode(np.fromstring(fhContents, dtype=np.uint8), cv2.IMREAD_COLOR)
like image 100
todbott Avatar answered Sep 13 '25 04:09

todbott