0

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.

1
  • 1
    " I visited the Google Drive website but there was a short piece of code." Could you link us to what you found? Commented Mar 24, 2021 at 19:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

After installing the packages, I ran the code and it gave me this error. ValueError: ('Unexpected credentials type', None, 'Expected', 'service_account') Although the credentials is in the same path.
I searched online to find the solution and I found to make the service account in the Google platform and then use that credentials file. I used it and it worked by printing the id of the folder_name but it didn't create the folder_name in google drive.
If it is created then how to make it visible?
I want to find the folder_name in google drive but it not there.
youtube.com/watch?v=uI220BJ0yXc In this video, a person created a folder in google drive it showed up in google drive.
|
0

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:

6 Comments

@fullfine you're doing same
What error are you getting? I forgot to change the scopes in the code, now it's updated. Delete the token.json and try again.
@fullfine raise exceptions.RefreshError(error_details, response_body) google.auth.exceptions.RefreshError: ('deleted_client: The OAuth client was deleted.', '{\n "error": "deleted_client",\n "error_description": "The OAuth client was deleted."\n}') [Finished in 1.3s with exit code 1] [cmd: ['/usr/bin/python3', '-u', '/home/bilal/Documents/Projects/Data_monitoring_project/Python_files/Google.py']] [dir: /home/bilal/Documents/Projects/Data_monitoring_project/Python_files] [path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games]
It seems that something happened with the OAuth client on the console. Try deleting the credentials.json and create a new one following the Python Quickstart. It is in the first step.
What type of credentials should be? Desktop app, web browser, web server. I don't which one to select.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.