在Google驱动器上创建一个文件夹(如果不存在),然后使用Python脚本将文件上传到该文件夹 [英] Create a folder (if not exists) on google drive and upload a file to it using Python script

查看:128
本文介绍了在Google驱动器上创建一个文件夹(如果不存在),然后使用Python脚本将文件上传到该文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So far I can upload file to the folder if it exists. I can't figure out a way to create one though. So if the folder does not exist, my script dies.

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()

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

Can you please help me modify the above code to create folder gpath if it does not exist?

推荐答案

基于文档,应该是

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

更新:截至2020年4月,文档(v3)已使用API​​文档进行了更新,并显示:

Update: As of Apr 2020, documentation (v3) has been updated with API docs and shows:

folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
file_metadata = {
    'name': 'photo.jpg',
    'parents': [folder_id]
}
media = MediaFileUpload('files/photo.jpg',
                        mimetype='image/jpeg',
                        resumable=True)
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

这篇关于在Google驱动器上创建一个文件夹(如果不存在),然后使用Python脚本将文件上传到该文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆