如何使用python在google drive中创建目录?

2024-05-14 00:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用python脚本创建目录。我花了一整天的时间寻找关于这个的教程,但是所有的帖子都是旧的。我访问了GoogleDrive网站,但有一段简短的代码。当我这样使用它的时候

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

它给了我以下错误

NameError: name 'drive_service' is not defined

我没有导入任何东西我不知道要导入哪个库?我只是使用这个代码。如何使用此代码或更新的代码在google drive中创建文件夹?我是初学者


Tags: 代码name目录脚本id网站servicegoogle
2条回答

请尝试以下代码:

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

您需要通过pip安装oath2clientgoogle-api-python-clienthttplib2

要进行检查,请选择所有文件夹:

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

顺便说一下:

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.

答复

我建议您按照这个guide开始使用驱动器API和Python。成功运行示例后,请将# Call the Drive v3 API上方的行替换为驱动器中的code文件夹。此外,为了创建文件夹,您必须修改作用域,在这种情况下,您可以使用https://www.googleapis.com/auth/drive.file。最终结果如下所示:

代码

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

参考资料:

相关问题 更多 >