6

I'm using PyDrive to upload files to Google Drive but could not figure out how to define the destination folder.

The following code saves a copy to the root on GDrive:

gauth = GoogleAuth() 
drive = GoogleDrive(gauth)
file1 = drive.CreateFile({'parent': '/home/pi'}) 
file1.SetContentFile('test.txt')
file1.Upload()

And how PyDrive returns the upload/download result?

Steve Robillard
  • 34,687
  • 17
  • 103
  • 109
Gilson
  • 91
  • 1
  • 1
  • 5

4 Answers4

6

First you need to obtain the id of the parent folder (the one you want to place files into). Use this code to do so:

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:       
    print ('title: %s, id: %s' % (file1['title'], file1['id']))
sys.exit()

save the folder id in a variable:

fid = '...'

Then, to add to the folder corresponding to that id, the client code is:

f = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": fid}]})
f.SetContentFile( some_path )
f.Upload()

You can get some info about the result:

print 'Created file %s with mimeType %s' % (f['title'], f['mimeType'])        
  • This answer shows how to upload a file to a specific folder, which is what I was looking for. Thanks – FindOutIslamNow Feb 03 '19 at 11:36
  • Where did you find the ""'root' in parents and trashed=false"" ? – Alex 75 Mar 15 '20 at 22:02
  • @Alex75 it's part of the query language. You can find examples here: https://developers.google.com/drive/api/v2/search-files#query_string_examples. I am wondering if there are keywords other than "root". – Matt Norris May 05 '20 at 17:45
4

This works:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
drive = GoogleDrive(gauth)

f = drive.CreateFile()
f.SetContentFile('document.txt')
f.Upload()
print('title: %s, mimeType: %s' % (f['title'], f['mimeType']))

file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
  print('title: %s, id: %s' % (file1['title'], file1['id']))
cLee
  • 41
  • 2
0

use like this,,

file1 = drive.CreateFile({'title': YOUR_FILE_NAME, 'parents': [{'id': ['YOUR_GOOGLE_FOLDER_ID']}]})

rocky
  • 1
0
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)


folderName = 'FOLDER NAME'  # 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({'title':'teste.txt','parents': [{'id': folder['id']}]})
        file2.Upload()
MatsK
  • 2,791
  • 3
  • 16
  • 20