【发布时间】:2019-04-11 10:13:19
【问题描述】:
我正在尝试使用此处的示例打开、读取、修改和关闭 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 文件名。
【问题讨论】:
-
当您从 Internet 复制代码时,并不能保证它确实有效。你有一个“打开”可以工作,一个不工作。您还会收到一条错误消息,告诉您为什么第二个不起作用。这应该可以为您提供足够的信息来解决问题。
-
顺便说一句,您在
with open(jsonFile, 'w') as jsonFIle:中输入了一个类型。as jsonFIle中有一个“I”而不是“i”。
标签: python json file contextmanager