首页 > 解决方案 > Google 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()

标签: pythongoogle-drive-apigoogle-api-clientpydrive

解决方案


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

如果我的理解是正确的,那么这个修改呢?

从:

file2 = drive.CreateFile()

至:

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

参考:

如果这不是你想要的结果,我很抱歉。

添加:

当你想从文件夹名称上传文件到特定文件夹时,这个修改怎么样?

从:

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']

推荐阅读