使用Service Account读取和下载Google Drive文件的代码总结
学习笔记作者:admin日期:2025-07-21点击:164
摘要:本文介绍了如何使用Python通过Service Account认证访问Google Drive,并列出文件和下载指定文件。包含完整的代码示例、依赖安装说明以及注意事项。
概述
本文提供了一个完整的Python脚本,用于通过Google Drive API使用Service Account进行认证,并实现列出Google Drive中的文件以及下载指定文件的功能。
认证部分
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
SERVICE_ACCOUNT_FILE = 'sa.json'
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)列出文件
def list_files():
    results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])
    if not items:
        print("没有找到文件。")
    else:
        print("文件列表:")
        for item in items:
            print(f"{item['name']} ({item['id']})")
    return items下载文件
from googleapiclient.http import MediaIoBaseDownload
import io
def download_file(file_id, file_name):
    request = service.files().get_media(fileId=file_id)
    fh = io.FileIO(file_name, 'wb')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while not done:
        status, done = downloader.next_chunk()
        print(f"下载进度: {int(status.progress() * 100)}%")
    print(f"文件 {file_name} 下载完成")主程序逻辑
if __name__ == '__main__':
    items = list_files()
    if items:
        first_file = items[0]
        print(f"正在下载: {first_file['name']} (ID: {first_file['id']})")
        download_file(first_file['id'], first_file['name'])注意事项
- 权限问题:Service Account需要被添加为文件或文件夹的协作者,授予“查看者”权限。
- 获取文件ID:Google Drive文件链接格式为 https://drive.google.com/file/d/FILE_ID/view,其中FILE_ID是所需的文件ID。
- 大文件下载:使用 MediaIoBaseDownload支持分块下载,适合大文件。
依赖安装
pip install google-api-python-client google-auth-httplib2 google-auth