Skip to main content
 首页 » 编程设计

python之构建路径之Google Drive SDK

2025年05月04日28arxive

我正在尝试使用 Python Google Drive API 为文件构建远程路径。给定一个路径,比如/folderA/FolderB/folderC/theFile.txt 我想在 Drive 上创建 folderA,然后在其中创建 folderB,然后在 B 中创建 folderC,然后再将文件上传到 folderC。

我有一个短循环:

currentParent = pathStartID 
for aFolder in pathArray: 
    thisFoldersID = self.createRemoteFolder(aFolder, parentID = currentParent) 
    currentParent = thisFoldersID 

我首先在 Drive root 中创建 folderA,folderA 的 ID 是“pathStartID”。 pathArray 包含文件夹 B 和文件夹 C 的名称。

createRemoteFolder() 

看起来像这样:

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['parentsCollection'] = [{'id': parentID}] 
        root_folder = driveFileMan.client.files().insert(body = body).execute() 
    return root_folder['id'] 

但出于某种原因,每个文件夹都在 Google Drive 的根目录中创建,而不是像我想要的那样在父文件夹中创建。

任何人都可以发现我做错了什么吗?或者有更简单的方法吗?

请您参考如下方法:

看起来只是设置父级的错误属性名称。尝试:

body['parents'] = [{'id': parentID}]