python - Google pydrive 将文件上传到特定文件夹

标签 python google-drive-api google-api-client pydrive

我正在尝试将文件上传到我的 Google 驱动器,下面的代码有效。
如何指定要上传到哪个文件夹,即驱动器---与我共享--csvFolder

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive


gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

file2 = drive.CreateFile()
file2.SetContentFile('new_test.csv')
file2.Upload()

最佳答案

  • 您想使用 pydrive 将文件上传到 Google Drive 中的特定文件夹。

  • 如果我的理解是正确的,这个修改怎么样?

    来自:
    file2 = drive.CreateFile()
    

    至:
    file2 = drive.CreateFile({'parents': [{'id': '### folder ID ###'}]})
    
  • 请像上面一样设置文件夹 ID。

  • 引用:
  • PyDrive’s documentation

  • 如果这不是您想要的结果,我深表歉意。

    补充:

    当您想从文件夹名称上传文件到特定文件夹时,如何修改?

    来自:
    file2 = drive.CreateFile()
    file2.SetContentFile('new_test.csv')
    file2.Upload()
    

    至:
    folderName = '###'  # Please set the folder name.
    
    folders = drive.ListFile(
        {'q': "title='" + folderName + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
    for folder in folders:
        if folder['title'] == folderName:
            file2 = drive.CreateFile({'parents': [{'id': folder['id']}]})
            file2.SetContentFile('new_test.csv')
            file2.Upload()
    

    获取文件夹 ID 的替代方法

    您可以使用以下代码段打印文件和/或文件夹 ID
    fileList = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
    for file in fileList:
      print('Title: %s, ID: %s' % (file['title'], file['id']))
      # Get the folder ID that you want
      if(file['title'] == "To Share"):
          fileID = file['id']
    

    关于python - Google pydrive 将文件上传到特定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56434084/

    相关文章:

    python - IBpy 获取订单状态更新

    python - 在线计算某个时间范围内的覆盖时间

    python - python 中的 Drive API 问题

    google-drive-api - 将 Google Drive 的默认文件夹更改为驱动器根目录? (D :)

    java - 无法识别 HttpTransport 类型的 create RequestFactory() 方法

    python - win32 : simulate a click without simulating mouse movement?

    python - DataFrame 的派生

    google-drive-api - Google Drive 和 CORS 跨域请求

    google-api-client - Google Slides API,图像在幻灯片上的定位

    android - 使用 Firebase 的 GoogleApiClient 中出现罕见的 NullPointerException