且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中使用Google Drive API创建新文件夹?

更新时间:2022-11-05 11:06:02

要在Drive上创建文件夹,请尝试:

To create a folder on Drive, try:

    def createRemoteFolder(self, folderName, parentID = None):
        # Create a folder on Drive, returns the newely created folders ID
        body = {
          'title': folderName,
          'mimeType': "application/vnd.google-apps.folder"
        }
        if parentID:
            body['parents'] = [{'id': parentID}]
        root_folder = drive_service.files().insert(body = body).execute()
        return root_folder['id']

如果您想在另一个文件夹中创建文件夹,则只需在此输入父ID,否则只是不要传递任何值。

You only need a parent ID here if you want to create folder within another folder, otherwise just don't pass any value for that.

如果您需要父级ID,则需要编写一种方法在该位置搜索具有该父级名称的文件夹(执行list()调用)然后获取该文件夹的ID。

If you want the parent ID, you'll need to write a method to search Drive for folders with that parent name in that location (do a list() call) and then get the ID of that folder.

编辑:请注意,API的v3使用父母字段的列表,而不是字典。此外,'title'字段已更改为'name' insert() 方法更改为 create()。从上面的代码将更改为以下v3:

Note that v3 of the API uses a list for the 'parents' field, instead of a dictionary. Also, the 'title' field changed to 'name', and the insert() method changed to create(). The code from above would change to the following for v3:

    def createRemoteFolder(self, folderName, parentID = None):
        # Create a folder on Drive, returns the newely created folders ID
        body = {
          'name': folderName,
          'mimeType': "application/vnd.google-apps.folder"
        }
        if parentID:
            body['parents'] = [parentID]
        root_folder = drive_service.files().create(body = body).execute()
        return root_folder['id']