Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyDrive: cannot write file to specific GDrive folder

I'm trying to copy files from a local machine to a specific folder in GDrive using PyDrive. If the target folder does not yet exist, I want to create it. Here is the relevant section of my code:

gfile = drive.CreateFile({'title':'dummy.csv', 
        'mimeType':'text/csv',
        'parent': tgt_folder_id})
gfile.SetContentFile('dummy.csv') 
gfile.Upload() # Upload it

I am definitely creating/finding the target folder correctly, and the tgt_folder_id is correct, but PyDrive always writes the file to the root folder of my Google Drive, not the target folder I've specified via the 'parent' parameter.

What am I doing wrong here?

like image 586
Chris Webster Avatar asked Apr 08 '14 10:04

Chris Webster


2 Answers

OK, looks like this is how you do it:

gfile = drive.CreateFile({'title':'dummy.csv', 'mimeType':'text/csv',
        "parents": [{"kind": "drive#fileLink","id": tgt_folder_id}]})

The "parents" map is used in the Google Drive SDK, which PyDrive is supposed to wrap. But the very few examples I've seen with PyDrive use "parent" and don't seem to work.

Anyway, hope this helps anybody else who hits the same problem.

like image 126
Chris Webster Avatar answered Sep 21 '22 19:09

Chris Webster


Ahoj @i-am-nik, to list subfolders you may use slightly altered line:

file_list = drive.ListFile({'q': 'trashed=false', 'maxResults': 10}).GetList()
for file1 in file_list:
  print('title: %s, id: %s' % (file1['title'], file1['id']))

This way it will list both folders and subfolders (of course, if you have many files, you may need to change maxResults value or add narrowing query.

like image 20
Mateusz Dąbrowski Avatar answered Sep 19 '22 19:09

Mateusz Dąbrowski