2015-12-05 94 views
2

我從PyDrive文檔中獲得以下代碼,該代碼允許訪問我的Google雲端硬盤中的頂級文件夾。我想訪問它的所有文件夾,子文件夾和文件。我該如何去做這件事(我剛開始使用PyDrive)?使用PyDrive訪問文件夾,子文件夾和子文件(Python)

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
from pydrive.auth import GoogleAuth 
from pydrive.drive import GoogleDrive 


gauth = GoogleAuth() 
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication 

#Make GoogleDrive instance with Authenticated GoogleAuth instance 
drive = GoogleDrive(gauth) 

#Google_Drive_Tree = 
# Auto-iterate through all files that matches this query 
top_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() 
for file in top_list: 
    print 'title: %s, id: %s' % (file['title'], file['id']) 
    print "---------------------------------------------" 

#Paginate file lists by specifying number of max results 
for file_list in drive.ListFile({'q': 'trashed=true', 'maxResults': 10}): 
    print 'Received %s files from Files.list()' % len(file_list) # <= 10 
    for file1 in file_list: 
     print 'title: %s, id: %s' % (file1['title'], file1['id']) 

我已經檢查了以下頁面How to list all files, folders, subfolders and subfiles of a Google drive folder,這似乎是我一直在尋找答案,但代碼是不存在了。

回答

2

您的代碼是絕對正確的。但使用Pydrive的默認設置,您只能訪問根級別的文件和文件夾。 更改settings.yaml文件中的oauth_scope可修復此問題。

client_config_backend: settings 
client_config: 
client_id: XXX 
client_secret: XXXX 

save_credentials: True 
save_credentials_backend: file 
save_credentials_file: credentials.json 

get_refresh_token: True 

oauth_scope: 
    - https://www.googleapis.com/auth/drive 
    - https://www.googleapis.com/auth/drive.metadata 
1

它需要迭代文件列表。根據this,代碼獲取文件夾中每個文件的文件和url鏈接的標題。代碼可以通過提供文件夾的id來獲得特定的文件夾,如ListFolder('id')。下面給出的例子是查詢root

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
from pydrive.auth import GoogleAuth 
from pydrive.drive import GoogleDrive 

gauth = GoogleAuth() 
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication 

#Make GoogleDrive instance with Authenticated GoogleAuth instance 
drive = GoogleDrive(gauth) 

def ListFolder(parent): 
    filelist=[] 
    file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % parent}).GetList() 
    for f in file_list: 
    if f['mimeType']=='application/vnd.google-apps.folder': # if folder 
     filelist.append({"id":f['id'],"title":f['title'],"list":ListFolder(f['id'])}) 
    else: 
     filelist.append({"title":f['title'],"title1":f['alternateLink']}) 
    return filelist 

ListFolder('root') 
+0

也許需要一些速率限制,雖然也 –

相關問題