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

如何使用python在google drive中创建目录?,python,python-3.x,google-drive-api,Python,Python 3.x,Google Drive Api,我想使用python脚本创建目录。我花了一整天的时间寻找关于这个的教程,但是所有的帖子都是旧的。我访问了GoogleDrive网站,但有一段简短的代码。当我这样使用它的时候 def createFolder(name): file_metadata = { 'name': name, 'mimeType': 'application/vnd.google-apps.folder' } file = drive_service.files().create(

我想使用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中创建文件夹?我是初学者。

试试下面的代码:

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安装
OATH2客户端
google api python客户端
httplib2

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

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
顺便说一下:

用户只能直接访问隐藏的应用程序文件夹中的数据 应用程序可以访问它们。这是为配置或其他目的而设计的 用户不应直接操作的隐藏数据。(用户 可以选择删除数据以释放数据使用的空间。)

用户能够访问它的唯一方法是通过一些功能 由特定应用程序公开

根据文件 你可以访问, 如果需要,请下载并操作这些文件。只是不是因为 普通谷歌硬盘用户界面

答复 我建议您遵循这一点,开始使用驱动器API和Python。运行示例后,请将上面的行替换为
#调用驱动器v3 API
,并将其替换为驱动器中的文件夹。此外,为了创建文件夹,您必须修改作用域,在这种情况下,您可以使用
https://www.googleapis.com/auth/drive.file
。最终结果如下所示:

代码 参考资料:

“我访问了Google Drive网站,但有一段简短的代码。”你能将我们链接到你发现的内容吗?安装软件包后,我运行了代码,它给了我这个错误
ValueError:(“意外凭据类型”,无,“预期”,“服务\u帐户”)
尽管凭据位于同一路径中。我联机搜索以找到解决方案,并在Google平台中找到创建服务帐户的方法,然后使用该凭据文件。我使用了它,它通过打印
文件夹名称的id来工作,但它没有在google drive中创建
文件夹名称
。如果创建了它,那么如何使其可见?我想在google drive中找到
文件夹名称
,但它不在那里。在这段视频中,一个人在google drive中创建了一个文件夹,它显示在google drive中。这段代码给了我一个错误。@fullfine你在做同样的事情。你得到了什么错误?我忘了更改代码中的作用域,现在它已更新。删除
token.json
并重试。@fullfine
引发异常。RefreshError(错误详细信息,响应正文)google.auth.exceptions.RefreshError:('deleted_客户端:OAuth客户端被删除','{\n“error:“deleted_客户端”,\n“error_description:“OAuth客户端被删除了”。\n}')[在1.3秒内完成,退出代码为1][cmd:['/usr/bin/python3','-u','/home/bilal/Documents/Projects/Data\u monitoring\u project/Python\files/Google.py'][dir:/home/bilal/Documents/Projects/Data\u monitoring\u project/Python\files][path:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/sbin:/usr/local/games:/usr/games:/sbin:/sbin:/bin:/bin:/bin:/bin:/usr:/usr:/usr
上的OAuth客户端似乎发生了一些问题。请尝试删除credentials.json并在之后创建一个新的credentials.json。这是第一步。
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()