我试图为我正在开发的机器人在config.json中存储一些数据,但每次我试图运行它时都会得到相同的错误。
我正在运行Python 3.7.3,这是重写的最新版本。我已经尝试在config.json文件中移动,但都没有用。我可能遗漏了一些非常明显的东西,但我不知道是什么。
在引发异常的地方:
with open("config.json", "r") as infile:
try:
CONFIG = json.load(infile)
_ = infile["token"]
_ = infile["owner"]
except (KeyError, FileNotFoundError):
raise EnvironmentError(
"Your config.json file is either missing, or incomplete. Check your config.json and ensure it has the keys 'token' and 'owner_id'"
)
预期结果:代码从文件中提取token
和owner
,并继续运行机器人。
实际结果:机器人没有启动。回溯输出-
File "/Users/prismarine/Desktop/Project_Prismarine/core.py", line 11, in <module>
_ = infile["token"]
TypeError: '_io.TextIOWrapper' object is not subscriptable
发布于 2019-05-23 07:21:23
您试图将文件句柄作为字典调用,而不是将存储在CONFIG
中的JSON字典调用。相反,请尝试:
with open("config.json", "r") as infile:
try:
CONFIG = json.load(infile)
token = CONFIG["token"]
owner = CONFIG["owner"]
except (KeyError, FileNotFoundError):
raise EnvironmentError(
"Your config.json file is either missing, or incomplete. Check your config.json and ensure it has the keys 'token' and 'owner_id'"
)
还请注意,如果不在任何地方使用下划线,则通常将下划线用作变量名,并且下划线将分配给CONFIG['token']
,然后在本例中立即重新分配给CONFIG['owner']
。如果您打算以后使用它们,我为它们指定了一些新的唯一变量名。
https://stackoverflow.com/questions/56266124
复制相似问题