简体   繁体   中英

How to create and show a folder in google drive using python script?

This code is showing the id of the folder_name but it is not showing up the folder_name in google drive. My purpose is to create and show the folder_name in google drive. How to do it?

import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

scope = 'https://www.googleapis.com/auth/drive'

credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
http = httplib2.Http()

drive_service = build('drive', 'v3', http=credentials.authorize(http))

def createFolder(name):
    file_metadata = {
        'name': name,
        'mimeType': 'application/vnd.google-apps.folder'
    }
    file = drive_service.files().create(body=file_metadata,
                                        fields='id').execute()
    print('Folder ID: %s' % file.get('id'))

createFolder('folder_name')

In your script, the folder is created by the service account. I think that this is the reason of your issue. The Google Drive of service account is different from your Google Drive. By this, the folder created by the service account cannot be seen in your Google Drive using the browser. When you want to see the folder created by the service account at the browser, how about the following flow?

  1. Create new folder in your Google Drive of your account.
    • Please create new folder in your Google Drive. In this case, you can create it using the browser.
  2. Share the created new folder with the email of the service account.
    • By this, your created folder in your Google Drive can be accessed by the service account.
    • The email address can be confirmed in the file of credentials.json .
  3. Create a folder to the shared folder using the service account with the script.

By this flow, I think that your goal can be achieved. For this, please modify your script as follows.

From:

file_metadata = {
    'name': name,
    'mimeType': 'application/vnd.google-apps.folder'
}

To:

file_metadata = {
    'name': name,
    'mimeType': 'application/vnd.google-apps.folder',
    'parents': ['### folder ID ###']
}
  • Please replace ### folder ID ### with your created folder ID in your Google Drive.
  • By above modification, the folder created by the script can be seen at your Google Drive using your browser.

Reference:

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