Manage files from public Google Drive URL using PyDrive

Filipe Spindola picture Filipe Spindola · Jun 20, 2016 · Viewed 8.4k times · Source

I`m using PyDrive QuickStart script to list my Google Drive files.

Code:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()

print(file_list)

I'm able to list my files normally, but I need to list and manage files from another public drive URL (which is not the my personal authenticated drive) from my already authenticated GoogleDrive account like if I was using requests lib. Any ideas how to do it?

Answer

Robin Nabel picture Robin Nabel · Jun 21, 2016
  1. You need to get the folder ID. You can find the ID in the URL of the folder. An example would be: https://drive.google.com/open?id=0B-schRXnDFZeX0t0RnhQVXXXXXX (the part of the URL after the id=).

  2. List contents of a folder based on ID. Given your code you replace file_list = ... with:

    file_id = '<Your folder id here.>'
    file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % file_id}).GetList()
    

    If this does not work, you may have to add the remote folder to your Google Drive using the "Add to Drive" button in the top right corner of the shared folder when opened in a browser.

    2.1 Creating a file in a folder can be done like so:

    file_object = drive.CreateFile({
                "parents": [{"kind": "drive#fileLink",
                             "id": parent_id}],
                'title': file_name,
                # (Only!) If the new 'file' object is going be a folder:
                'mimeType': "application/vnd.google-apps.folder"
            })
    file_object.Upload()
    

    If this fails check whether you have write permissions to the folder.

    2.2 Deleting/Trashing a file can be done with the updated version available from GitHub: pip install instructions, Delete/Trash/UnTrash documentation

Finally, there is a feature request to Upload to folders as described in 2.1, and listing files of a folder, as described in 2. - if you find the above not to work you can add this as an issue / feature request to the repository.