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

时间:2023-01-25
本文介绍了如何在 Python 中使用 Google Drive API 创建新文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

来自这个例子.我可以使用 MediafileUpload 创建文件夹吗?如何获取 parent_id?

From this example. Can I use MediafileUpload with creating folder? How can I get the parent_id from?

来自 https://developers.google.com/drive/folder

我只知道我应该使用 mime = "application/vnd.google-apps.folder" 但是如何实现本教程以使用 Python 进行编程?

I just know that i should use mime = "application/vnd.google-apps.folder" but how do I implement this tutorial to programming in Python?

感谢您的建议.

推荐答案

要在云端硬盘上创建文件夹,请尝试:

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,则需要编写一个方法来在该位置搜索 Drive 以查找具有该父名称的文件夹(执行 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']

这篇关于如何在 Python 中使用 Google Drive API 创建新文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!