You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Google Calendar API时遇FileNotFoundError:找不到credentials.json文件

解决Google Calendar API的FileNotFoundError问题

你遇到的错误:

FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json'

你的当前代码:

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials
import requests 
import os
import datetime
import json
from requests.structures import CaseInsensitiveDict
scopes = ['https://www.googleapis.com/auth/calendar']
#flow = InstalledAppFlow.from_client_secrets_file("client_secrets_file.json", scopes=scopes) from previous attempts
#credentials = flow.run_console()    this too

def main():
    creds=None
    if os.path.exists('token.json'):
        creds=Credentials.from_authorized_user_file('token.json',scopes)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow= InstalledAppFlow.from_client_secrets_file('credentials.json',scopes)
            creds=flow.run_local_server(port=0)
        with open('token.json','w') as token:
            token.write(creds.to_json())

if __name__ == '__main__':
    main()

解决方法:

  • 获取合法的credentials.json文件
    登录Google Cloud控制台,进入你的项目,在「API和服务」→「凭据」页面,创建「桌面应用」类型的OAuth 2.0客户端ID,下载生成的JSON文件,将其重命名为credentials.json。

  • 确保文件路径正确
    将credentials.json放在Python脚本的同一目录下;如果放在其他位置,要在代码里写完整的绝对路径,比如:

    flow= InstalledAppFlow.from_client_secrets_file('/你的文件完整路径/credentials.json', scopes)
    
  • 修复代码中的导入错误
    代码里的creds.refresh(Request())调用缺少对应的类导入,需要在文件开头添加:

    from google.auth.transport.requests import Request
    

内容的提问来源于stack exchange,提问作者imsolost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 09:40:16