Python script for managing Google Drive folders and documents

Hey everyone! I’m new to Python and I’m trying to work with the Google Drive API. I want to make a script that can do a few things:

  1. Create a folder if it doesn’t exist already
  2. Add a new document to that folder
  3. Get a list of all the docs in the folder with their links

I’ve started with this code:

import gdrive_helper

config = {
    'app_name': 'MyDriveManager',
    'user_email': '[email protected]',
    'password': 'mypassword'
}

drive = gdrive_helper.DriveClient(config)

new_folder = drive.create_folder('My New Folder')
new_doc = drive.create_document('Test Doc', parent=new_folder)

# How do I check if the folder exists?
# How do I get only the contents of this folder?
# How do I get the full URLs of the docs?

I’m using some made-up gdrive_helper module here. Can anyone help me figure out how to do those last three things? Thanks!

I’ve dealt with similar tasks using the Google Drive API and found a few workarounds that may help.

To check if a folder exists, you can call drive.files().list() with a query such as “name=‘My New Folder’ and mimeType=‘application/vnd.google-apps.folder’”. That will return any folders matching the criteria.

For retrieving the contents of a folder, use drive.files().list() with a query like “‘folder_id’ in parents”, replacing folder_id with the actual ID of your folder.

Finally, to construct full URLs for your documents, use a format like “https://drive.google.com/file/d/{file_id}/view”, where file_id is obtained from the API response. Just be sure to handle pagination if you have many files and confirm you are using the latest version of the Google Client Library for Python.

hey alex, i’ve worked with google drive api before. for checking if folder exists, try using drive.files().list() with a query parameter. to get folder contents, use the same method with the folder’s ID as parent. for full URLs, you can construct them using the file IDs. hope this helps! let me know if u need more details

I’ve found that using the Google Drive API v3 can simplify these tasks considerably. For folder existence, you can use the files().list() method with a query like “name=‘My New Folder’ and mimeType=‘application/vnd.google-apps.folder’”. This returns matching folders.

To get folder contents, use files().list() again, but with the query “‘folder_id’ in parents”. Replace folder_id with your actual folder ID.

For document URLs, you can construct them using the format “https://docs.google.com/document/d/{doc_id}/edit”. The doc_id is available in the API response.

Remember to handle pagination for large folders and always use the latest Google Client Library for Python to ensure compatibility and access to the most recent features.