小编A T*_*A T的帖子

类型错误:预期的 str、bytes 或 os.PathLike 对象,而不是 _io.TextIOWrapper

我正在尝试使用此处的示例打开、读取、修改和关闭 json 文件:

如何向使用 Python 从文件中检索的 JSON 数据添加键值?

import os
import json

path = '/m/shared/Suyash/testdata/BIDS/sub-165/ses-1a/func'
os.chdir(path)

string_filename = "sub-165_ses-1a_task-cue_run-02_bold.json"

with open ("sub-165_ses-1a_task-cue_run-02_bold.json", "r") as jsonFile:
    json_decoded = json.load(jsonFile)

json_decoded["TaskName"] = "CUEEEE"

with open(jsonFile, 'w') as jsonFIle:
    json.dump(json_decoded,jsonFile) ######## error here that open() won't work with _io.TextIOWrapper
Run Code Online (Sandbox Code Playgroud)

最后我不断收到错误消息(open(jsonFile...)因此我不能使用jsonFile变量 with open()。我使用了上面链接中提供的示例的确切格式,所以我不确定为什么它不起作用。这最终会进入更大的脚本,所以我想远离硬编码/使用字符串作为 json 文件名。

python json file contextmanager

7
推荐指数
1
解决办法
2万
查看次数

标签 统计

contextmanager ×1

file ×1

json ×1

python ×1