【问题标题】:Fixing "TypeError: '_io.TextIOWrapper' object is not subscriptable" in python script在 python 脚本中修复“TypeError:'_io.TextIOWrapper' 对象不可下标”
【发布时间】:2019-10-09 11:47:20
【问题描述】:

我正在尝试将一些数据存储在我正在处理的机器人的 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'"
        )

预期结果:代码从文件中提取 tokenowner,然后继续运行机器人。

实际结果:机器人没有启动。回溯输出 -

  File "/Users/prismarine/Desktop/Project_Prismarine/core.py", line 11, in <module>
    _ = infile["token"]
TypeError: '_io.TextIOWrapper' object is not subscriptable

【问题讨论】:

  • 您将 json 保存在 CONFIG...看来您应该在其中查找令牌和所有者。

标签: python json discord discord.py discord.py-rewrite


【解决方案1】:

您尝试将文件句柄作为字典调用,而不是存储在 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']。如果您打算以后使用它们,我给了它们一些新的唯一变量名称。

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2016-12-05
    • 2016-07-23
    • 2016-08-20
    • 2020-01-30
    • 1970-01-01
    • 2021-11-29
    • 2015-12-18
    相关资源
    最近更新 更多