无法访问token.json:没有这个文件或目录 Python。

4
我正在尝试通过Python访问Gmail API。这里是说明。 我已将credentials.json(我也复制了一份并将其重命名为token.json,并将其添加到主文件夹中)和quickstart.py文件放在主文件夹中。我在cmd和Atom IDE中运行quickstart.py,但是出现了以下错误:
    C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\_helpers.py:255: UserWarning: Cannot access token.json: No such file or directory  
     warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
    Traceback (most recent call last):

  File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\clientsecrets.py", line 121, in _loadfile
    with open(filename, 'r') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\HP Pavilion\Documents\Atom\Gmail\quickstart.py", line 34, in <module>
    main()
  File "C:\Users\HP Pavilion\Documents\Atom\Gmail\quickstart.py", line 18, in main
    flow = client.flow_from_clientsecrets("credentials.json", SCOPES)
  File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\client.py", line 2135, in flow_from_clientsecrets
    cache=cache)
  File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\clientsecrets.py", line 165, in loadfile
    return _loadfile(filename)
  File "C:\Users\HP Pavilion\AppData\Local\Programs\Python\Python36\lib\site-packages\oauth2client\clientsecrets.py", line 125, in _loadfile
    exc.strerror, exc.errno)
oauth2client.clientsecrets.InvalidClientSecretsError: ('Error opening file', 'credentials.json', 'No such file or directory', 2)

看起来.json文件找不到。但它们确实在同一个文件夹中。我还尝试以管理员身份运行代码,但没有任何成功。

4个回答

2
我不确定你发生了什么事情,但我用PyCharm或VS Code运行这个脚本时运行得很完美。 唯一的前提条件(可能你跳过了这一步)是你应该先生成credentials.json文件,下载它并将它放到与python脚本相同的目录中。此外,我创建了一个空的tokens.json文件。 首先,它会自动打开你的默认浏览器以指示你要指定哪个Gmail帐户。接下来,它将输出你的Gmail帐户的标签。

1
我的错误在于右键点击了我的JSON文件,选择重命名,然后将其命名为credentials.JSON,这使得真正的文件名为credentials.JSON.JSON。

5
这可能是一条评论。 - Yash Yadav

0

如果它与脚本位于同一位置,您可以尝试:

import os
path = os.path.abspath('credentials.json')
with open(path,'r'):
  //code

0

我曾经遇到同样的问题,最终发现问题出在我使用的IDE上(Mu 1.1.0)。一旦我下载了JSON文件并将其重命名后,将其放置在指向错误的目录中,并使用cmd运行所有内容,它就按预期工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接