在Google云端硬盘上创建一个文件夹(如果不存在),并使用Python脚本将文件上传到该文件夹

Aks*_*tgi 7 python google-api-python-client pydrive

到目前为止,我可以将文件上传到该文件夹​​(如果存在).我不知道如何创建一个.因此,如果文件夹不存在,我的脚本就会死掉.

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

gpath = '2015'
fname = 'Open Drive Replacements 06_01_2015.xls'

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
    if file1['title'] == gpath:
        id = file1['id']

file1 = drive.CreateFile({'title': fname, "parents":  [{"kind": "drive#fileLink","id": id}]})
file1.SetContentFile(fname)
file1.Upload()
Run Code Online (Sandbox Code Playgroud)

你可以帮我修改上面的代码来创建文件夹gpath,如果它不存在吗?

Gur*_*gde 10

根据文档,它应该是

file1 = drive.CreateFile({'title': fname, 
    "parents":  [{"id": id}], 
    "mimeType": "application/vnd.google-apps.folder"})
Run Code Online (Sandbox Code Playgroud)

  • 为了完整起见,您还需要在上述之后对 `file1` 调用 `.Upload()` 以实际提交操作。`file1['id']` 将包含所创建文件夹的 `id`。 (3认同)