简体   繁体   English

Pydrive创建文件夹+上传文件

[英]Pydrive create folder + upload file

I would like to create a folder on Google drive and then upload files to Google drive using Pydrive My codes are working separately, but I would like to do it in 1 step.我想在 Google 驱动器上创建一个文件夹,然后使用 Pydrive 将文件上传到 Google 驱动器我的代码是单独工作的,但我想一步完成。

Code to create folder创建文件夹的代码

gauth = GoogleAuth()
drive = GoogleDrive(gauth)

folder_name = 'My_new_folder'
folder = drive.CreateFile({'title' : folder_name, 'mimeType' : 'application/vnd.google-apps.folder'})
folder.Upload()

And here is my code for uploading the files to the above folder这是我将文件上传到上述文件夹的代码

folder = '15nBytebfWboTpbF4NmzUiorlrhszope'

directory = "C:/Users/Singh/screenshots/"
for f in os.listdir(directory):
    filename = os.path.join(directory, f)
    files= drive.CreateFile({'parents' : [{'id' : folder}], 'title' : f})
    files.SetContentFile(filename)
    files.Upload()

How can I join these 2 steps together?我怎样才能将这两个步骤结合在一起? So first create a folder and then upload the files to that folder on Google Drive因此,首先创建一个文件夹,然后将文件上传到 Google Drive 上的该文件夹

You can try this code to create a folder and upload a file in one step:您可以尝试使用此代码一步创建文件夹并上传文件:

# Create folder
folder_name = 'My_new_folder'
folder_metadata = {'title' : folder_name, 'mimeType' : 'application/vnd.google-apps.folder'}
folder = drive.CreateFile(folder_metadata)
folder.Upload()

# Upload file to folder
folderid = folder['id']
file = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": folderid}]})
file.SetContentFile('testfile.txt')
file.Upload()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM