7

My Google Drive looks something like this:

picture1.jpg

song1.mp3

a/b/file1.txt

a/b/file2.txt

a/b/file3.jpg

a/b/file4.m4a

a/b/...

I want to use PyDrive to download every file in folder "b". After looking at the documentation and checking StackOverflow, I still cannot figure out how to do this. How would I download all of the files in folder "b" (which is contained in folder "a") using PyDrive. Also, in case it's relevant please note that folder "b" contains thousands of files.

Community
  • 1
  • 1
James Shapiro
  • 4,805
  • 3
  • 31
  • 46

1 Answers1

13

I figured it out. Basically you need to use the file id to list or download a folder's contents.

Assuming that file_list is the root directory:

for file1 in file_list:
    if file1['title'] == '[name_of_target_folder]':
        folder_id = file1['id']

Then

> folder_id 
> 'WIU1xyz19g83abcdefg'

(for example)

get every file in 'folder':

file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format(folder_id)}).GetList()

download every file in 'folder':

for i, file1 in enumerate(sorted(file_list, key = lambda x: x['title']), start=1):
    print('Downloading {} from GDrive ({}/{})'.format(file1['title'], i, len(file_list)))
    file1.GetContentFile(file1['title'])
tuomastik
  • 4,559
  • 5
  • 36
  • 48
James Shapiro
  • 4,805
  • 3
  • 31
  • 46
  • 2
    Downloading each file individually seems incredibly slow when I run it. Is there no way to just grab an entire directory at once? – sh37211 Apr 27 '19 at 04:30
  • @james - I have around 30K files and the ListFile command takes ages - is there any recommendation ?! – Areza Feb 14 '20 at 22:33
  • 1
    @user702846 I think this is probably what you're looking for: https://pythonhosted.org/PyDrive/filelist.html#paginate-and-iterate-through-files (see the second section on pagination/iteration). – James Shapiro Feb 15 '20 at 10:59