TransWikia.com

Use PyDrive to upload files to Google Drive folder

Raspberry Pi Asked by Gilson on November 8, 2021

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?

4 Answers

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

Answered by GABRIEL LOPES DOS SANTOS on November 8, 2021

use like this,,

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

Answered by rocky on November 8, 2021

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'])        

Answered by user5555 on November 8, 2021

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']))

Answered by cLee on November 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP