Search code examples
pythonpydrive

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.

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


Solution

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