0

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

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
Singh
  • 80
  • 7

1 Answers1

0

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()
liketaurus
  • 152
  • 5