To list all files in Google drive directory by through a python script using Pydrive module














































To list all files in Google drive directory by through a python script using Pydrive module



Steps :
  1. The all important code :
    1. # To List all files of G-drive with thier names and MimeType
    2. from pydrive.drive import GoogleDrive

    3. drive = GoogleDrive(gauth)
    4. fileList = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
    5. flag = False
    6. for file in fileList:
    7.     if(file['mimeType'] != "application/vnd.google-apps.folder"):
    8.         print('Title: %s, ID: %s, mimeType: %s \n\n' % (file['title'], file['id'], file['mimeType']))
    9.         flag = True
    10. if(not flag):
    11.     print("Sorry! no file found....")
  2. In the above program you are importing GoogleDrive class from pydrive.drive library in line 2
  3. In line 4 you are creating an object 'drive' of the GoogleDrive class and are simultaneously passing the 'gauth' object of GoogleAuth class which you had created earlier to give your access to your G drive account.
  4. In line 5 you are calling ListFile method through the drive object and are passing and telling about directory from which you wish to list out the files ('root' in the above example). Do remember to false the trashed argument if you don't want to list out the files which have been trashed already.
  5. This ListFile method of GoogleDrive class returns a dictionary with multiple types of keys. In line 6 we are trying to traverse this iterable returned from the ListFile method
  6. In line 7 we are testing each element of this fileList for it's mimeType (which indicates the type of file) as being a file or not and For all true case we display the file along with it's name('title') and id.

After running the code in a suitable ide you will get the following output :



If you want to look at the Google drive account for this output instance :


Comments