首页 > 解决方案 > text io wrapper error 事情我很困惑

问题描述

k 所以我有代码,它工作得很好。launcher.py 运行所有这些,所以如果事情看起来不像正在执行,它们只是来自另一个位置。我不断收到一个看起来像这样的错误:

File "C:\<personal directories>\Python\Python39\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type TextIOWrapper is not JSON serializable

我不知道为什么会这样。我能得到一些帮助吗?我可能遗漏了一些愚蠢的东西,但我试图在其他地方找到这个错误。
下面的代码:

    parent_dir = os.getcwd()
    created_dir = r"\Profiles"
    script_dir = parent_dir + created_dir
    profiles_path = os.path.join(script_dir, "Profiles.txt")
    try:
        with open(profiles_path, "r") as profile_file:
            profile_list = profile_file.read()
        print(profile_list)
    except IndexError:
        print("err")
    opening_question = input("please type the name of the profile you would like to enter. (case sensitive) \n \n $")

    parent_dir = os.getcwd()
    created_dir = r"\Profiles"
    script_dir = parent_dir + created_dir
    file_name = opening_question
    file_extention = ".json"
    file_dir = file_name + file_extention
    file_path = os.path.join(script_dir, file_dir)

    with open(profiles_path, 'r'):
        if opening_question in profile_list:
            with open(file_dir) as open_file:
                open_file = json.dumps(open_file, indent=2, sort_keys=True)
            print(open_file)
        else:
            print("Unknown choice", opening_question)```

标签: pythonjsonpython-3.x

解决方案


您需要读取文件的内容并将内容传递给json.dumps文件对象本身

要阅读内容,您可以使用 file.read 例如 -

with open(profiles_path, 'r'):
        if opening_question in profile_list:
            with open(file_dir) as open_file:
                file_content = open_file.read()
                json_dump = json.dumps(file_content, indent=2, sort_keys=True)
            print(json_dump)
        else:
            print("Unknown choice", opening_question)

推荐阅读