You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PyDrive避免在Google Drive中重复创建同名文件夹?

解决Google Drive重复创建同名日期文件夹的问题

你可以通过先查询目标文件夹是否存在的方式避免重复创建,具体是利用Google Drive API的文件列表查询功能,在指定父目录下查找同名且未被删除的文件夹。修改后的代码如下:

def CreateGDriveFolder(self):
    from datetime import date
    import time

    today = str(date.today())
    print("Todays Date: " + today) 
    gauth = GoogleAuth()
    self.drive = GoogleDrive(gauth)

    folder_name = today
    parent_folder_id = '1k1kFXJa1MTlAQrkPE0uKW-kO3Hj1Bjp5'

    # 构造查询条件:查找指定父目录下、同名、未被删除的文件夹
    query = f"mimeType='application/vnd.google-apps.folder' and title='{folder_name}' and parents='{parent_folder_id}' and trashed=false"
    existing_folders = self.drive.ListFile({'q': query}).GetList()

    if existing_folders:
        # 文件夹已存在,直接获取已有文件夹的信息
        folder = existing_folders[0]
        print("Folder already exists")
    else:
        # 文件夹不存在,创建新文件夹
        folder = self.drive.CreateFile({
            'title': folder_name,
            'mimeType': 'application/vnd.google-apps.folder',
            'parents': [{'id': parent_folder_id}]
        })
        time.sleep(2)
        folder.Upload()
        print("Folder Created")

    # 更新文件夹信息到实例变量
    self.foldertitle = folder['title']
    self.folderid = folder['id']
    print('title: %s, id: %s' % (self.foldertitle, self.folderid))

关键说明:

  • 查询参数q:组合四个条件,确保只匹配目标父目录下、名称为当日日期、未被移入回收站的文件夹,避免误判
  • 结果判断:GetList()返回的列表不为空时,说明存在对应文件夹,直接使用第一个结果(Google Drive允许同名文件夹,这里默认取第一个即可)
  • 逻辑复用:不管文件夹是已存在还是新创建,最后统一提取标题和ID到实例变量,后续上传文件时直接使用self.folderid作为父目录ID即可

内容的提问来源于stack exchange,提问作者Dilshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:45:43