【发布时间】:2021-02-20 01:48:28
【问题描述】:
为什么我不能导入与我要导入的代码位于同一文件夹中的文件?我在 Visual Studio Code 中工作。
这是我的代码:
import requests
import json
import webbrowser
import credentials
from pprint import pprint
r = requests.get("https://api.thecatapi.com/v1/favourites",
headers=credentials.headers)
try:
content = r.json
except json.decoder.JSONDecodeError:
print("Wrong format")
else:
pprint(content)
这是标签弹出的问题。
Import "credentials" could not be resolved
这是导入文件的内容。
headers = {"x_api_key": "xxxxxxxxxxxxxxxxxx"}
【问题讨论】:
-
你能发布 full 和 exact 错误信息吗?它通常有更多信息,比如哪一行引发了错误。因为这看起来不像来自 Python 的标准导入错误。而“标签弹出”中的“tab”又是什么?
-
试试
import .credentials。在 Python 3 中,默认情况下导入是绝对的,您需要添加 '.'使它们相对(在这种情况下,相对于当前目录)。 - 我希望您使用某种语法检查器,可能是因为 VSC 已经设置了它。我相信,该错误来自检查器,而不是 Python 解释器。 -
你有
__init__.py文件吗? -
以上所有答案都得感悟。当两个文件在同一个文件夹中时,它们可以毫无问题地导入。这里的问题是文件名。
标签: python visual-studio-code importerror