类型错误:应为str、bytes或os.PathLike对象,而不是io.TextIOWrapp

2024-06-17 12:48:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用以下示例打开、读取、修改和关闭一个json文件:

How to add a key-value to JSON data retrieved from a file with Python?

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

我总是在结尾处得到一个错误(带有open(jsonFile...),我不能将jsonFile变量与open()一起使用)。我使用了上面链接中提供的确切格式作为示例,所以我不确定为什么它不起作用。这最终将进入一个更大的脚本,因此我希望避免硬编码/使用json文件名的字符串。


Tags: topathrunimportjson示例taskos