Skip to content Skip to sidebar Skip to footer

Google Pydrive Uploading A File To Specific Folder

I am trying to upload a file to my Google drive, the code below works. How can I specify to which folder to upload to i.e drive---shared with me--csvFolder from pydrive.auth import

Solution 1:

  • You want to upload a file to the specific folder in your Google Drive using pydrive.

If my understanding is correct, how about this modification?

From:

file2 = drive.CreateFile()

To:

file2 = drive.CreateFile({'parents': [{'id': '### folder ID ###'}]})
  • Please set the folder ID like above.

Reference:

If this was not the result you want, I apologize.

Added:

When you want to upload a file to the specific folder from the folder name, how about this modification?

From:

file2 = drive.CreateFile()
file2.SetContentFile('new_test.csv')
file2.Upload()

To:

folderName = '###'# Please set the folder name.

folders = drive.ListFile(
    {'q': "title='" + folderName + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
for folder in folders:
    if folder['title'] == folderName:
        file2 = drive.CreateFile({'parents': [{'id': folder['id']}]})
        file2.SetContentFile('new_test.csv')
        file2.Upload()

Alternative to get folder ID

You can use the following snippet to print files and or folders ID

fileList = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file in fileList:
  print('Title: %s, ID: %s' % (file['title'], file['id']))
  # Get the folder ID that you wantif(file['title'] == "To Share"):
      fileID = file['id']

Post a Comment for "Google Pydrive Uploading A File To Specific Folder"