Python JSON error: The JSON object must be str, bytes or bytearray, not TextIOWrapper
Python JSON error: The JSON object must be str, bytes or bytearray, not TextIOWrapper
所以我在这里收到这个错误:
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
当我 运行 此代码时发生此错误:
def changeusername():
print("Change Your Username:")
username = str(input(">>> "))
with open('settings/userInfo.json', 'w') as f:
tempholder = json.loads(f)
tempholder['Username'] *= username
f.seek(0)
f.write(json.dumps(tempholder))
print("Changed Name.")
基本上我有这个 JSON 文件,其中有一个“用户名”字符串元素。我想将字符串元素更改为我的输入,然后保存以备后用。文件位置正确,所有代码都可以在没有实际 JSON 函数的情况下工作。我还导入了 JSON 模块。总之,谢谢你的帮助!
@Barmar 关于 json.loads 与 json.load 的精彩评论是错误的关键。下面是一些将代码改进到工作状态的更多提示。
在 python 中,在同一上下文管理器中读取文件并将内容写回文件可能会很棘手。
更稳健的解决方案可能是使用两个单独的 with 块。
看看这个答案,虽然没有 json,但它似乎提供了您想做的事情的代码。
下面的代码适合我
print("Change Your Username:")
username = str(input(">>> "))
with open('settings/userInfo.json', 'r') as f:
currentFileData = json.load(f)
currentFileData['Username'] = username
with open('settings/userInfo.json', 'w') as f:
f.write(json.dumps(currentFileData))
print("Changed Name.")
编辑:
感谢您在同一块中对 reading/writing 的提醒。确实不是不可能。
还调整了示例代码中的一处错别字。
在示例代码中将文件位置调整回 Ops 原始文件路径。
所以我在这里收到这个错误:
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
当我 运行 此代码时发生此错误:
def changeusername():
print("Change Your Username:")
username = str(input(">>> "))
with open('settings/userInfo.json', 'w') as f:
tempholder = json.loads(f)
tempholder['Username'] *= username
f.seek(0)
f.write(json.dumps(tempholder))
print("Changed Name.")
基本上我有这个 JSON 文件,其中有一个“用户名”字符串元素。我想将字符串元素更改为我的输入,然后保存以备后用。文件位置正确,所有代码都可以在没有实际 JSON 函数的情况下工作。我还导入了 JSON 模块。总之,谢谢你的帮助!
@Barmar 关于 json.loads 与 json.load 的精彩评论是错误的关键。下面是一些将代码改进到工作状态的更多提示。
在 python 中,在同一上下文管理器中读取文件并将内容写回文件可能会很棘手。
更稳健的解决方案可能是使用两个单独的 with 块。
看看这个答案,虽然没有 json,但它似乎提供了您想做的事情的代码。
下面的代码适合我
print("Change Your Username:")
username = str(input(">>> "))
with open('settings/userInfo.json', 'r') as f:
currentFileData = json.load(f)
currentFileData['Username'] = username
with open('settings/userInfo.json', 'w') as f:
f.write(json.dumps(currentFileData))
print("Changed Name.")
编辑: 感谢您在同一块中对 reading/writing 的提醒。确实不是不可能。
还调整了示例代码中的一处错别字。
在示例代码中将文件位置调整回 Ops 原始文件路径。