简体   繁体   中英

How to create directories in google drive using python?

I want to create directories using python script. I spent the whole day finding a tutorial about this but all the posts were old. I visited the Google Drive website but there was a short piece of code. When I used it like this,

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'))

It gave me the following error

NameError: name 'drive_service' is not defined

I didn't import anything I don't know which library to import? I just use this code. How to use this or updated code to create folders in google drive? I am a beginner.

Try this code:

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

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

# `client_secrets.json` should be your credentials file, as generated by Google.
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.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')

You will need to install oath2client , google-api-python-client and httplib2 via pip.

To check, all of the folders:

page_token = None

while True:
    response = drive_service.files().list(q="mimeType='application/vnd.google-apps.folder'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):
        # Process change
        print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
    page_token = response.get('nextPageToken', None)
    if page_token is None:
        break

By the way:

The user cannot directly access data in the hidden app folders, only the app can access them. This is designed for configuration or other hidden data that the user should not directly manipulate. (The user can choose to delete the data to free up the space used by it.)

The only way the user can get access to it is via some functionality exposed by the specific app.

According to documentation https://developers.google.com/drive/v3/web/appdata you can access, download and manipulate the files if you want to. Just not though the normal Google Drive UI.

Answer

I recommend you to follow this guide to start working with the Drive API and Python. Once you have managed to run the sample, replace the lines above # Call the Drive v3 API with this code that a folder in your Drive. Furthermore, you have to modify the scopes in order to create a folder, in this case, you can use https://www.googleapis.com/auth/drive.file . The final result looks like this:

Code

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.file']

def main():
    """Shows basic usage of the Drive v3 API.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    folder_name = 'folder A'
    file_metadata = {
        'name': folder_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'))

if __name__ == '__main__':
    main()

References:

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