簡體   English   中英

如何列出特定谷歌驅動器目錄 Python 中的所有文件

[英]How to list all the files in a specific google drive directory Python

按文件夾 ID 列出特定谷歌驅動器目錄的所有文件的最佳方法是什么。 如果我構建如下所示的服務,下一步是什么? 找不到任何對我有用的東西。 此示例中的 Service_Account_File 是帶有令牌的 json 文件。

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = service_account_file 
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('drive', 'v3', credentials=credentials)

file.list 方法有一個名為 q 的參數。 您可以使用 q 搜索目錄中的文件等內容。

假設您知道正在查找的文件夾的文件 ID,您將執行“folderid 中的父母”

這將返回該文件夾中的所有文件。

page_token = None
while True:
    response = drive_service.files().list(q="parents in 'YOURFOLDERIDHERE'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):
        # Process change
        print 'Found file: %s (%s)' % (file.get('name'), file.get('id'))
    page_token = response.get('nextPageToken', None)
    if page_token is None:
        break

我相信你的目標如下。

  • 您想使用 python 的服務帳戶檢索特定文件夾下的文件列表。

在這種情況下,我想提出以下兩種模式。

模式一:

在此模式中,使用 python 的 googleapis 驅動器 API 中的“文件:列表”方法。 但在這種情況下,不會檢索特定文件夾中子文件夾中的文件。

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = service_account_file
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)

topFolderId = '###' # Please set the folder of the top folder ID.

items = []
pageToken = ""
while pageToken is not None:
    response = service.files().list(q="'" + topFolderId + "' in parents", pageSize=1000, pageToken=pageToken, fields="nextPageToken, files(id, name)").execute()
    items.extend(response.get('files', []))
    pageToken = response.get('nextPageToken')

print(items)
  • q="'" + topFolderId + "' in parents"表示在topFolderId的文件夾下檢索文件列表。
  • 使用pageSize=1000時,可以減少Drive API的使用次數。

模式二:

在此模式中,使用了一個getfilelistpy庫。 在這種情況下,也可以檢索特定文件夾中子文件夾中的文件。 首先,請按如下方式安裝庫。

$ pip install getfilelistpy

示例腳本如下。

from google.oauth2 import service_account
from getfilelistpy import getfilelist

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = service_account_file
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

topFolderId = '###' # Please set the folder of the top folder ID.
resource = {
    "service_account": credentials,
    "id": topFolderId,
    "fields": "files(name,id)",
}
res = getfilelist.GetFileList(resource)
print(dict(res))
  • 在這個庫中,可以使用驅動器API中的“文件:列表”的方法搜索特定文件夾中的子文件夾,googleapis for python。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM