python - 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)```
解决方案
您需要读取文件的内容并将内容传递给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)
推荐阅读
- javascript - 如何修复javascript中的settimeout内存泄漏问题
- sql - 使用来自子查询的多个值进行更新
- c++ - 通过函数释放内存 - 这是对的吗?
- sql - 如何使用 distinct 和 sum 编写 SQL 报告
- python - 将多索引数据帧写入 csv 而不更改其格式
- php - PHP Wordpress:在 Safari 中 print_r() 输出到哪里?
- regex - RegEx 用于匹配逗号前的单词,但有例外
- c# - 将 Xamarin.Forms 从 2.xx 升级到 3.xx 时出错
- sql - 在 OVER 子句中使用 ORDER BY
- r - 是否有用于取消哈希数据的 R 函数(相当于 Python 中的“hashlib”函数)?