A T*_*A T 7 python json file contextmanager
我正在尝试使用此处的示例打开、读取、修改和关闭 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 文件名。
这个问题有点旧,但对于任何有同样问题的人:
你是对的,你不能打开 jsonFile 变量。它是一个指向另一个文件连接的指针,并且 open 需要一个字符串或类似的东西。值得注意的是,一旦您退出 'with' 块, jsonFile 也应关闭,因此不应在此之外引用它。
不过要回答这个问题:
with open(jsonFile, 'w') as jsonFIle:
json.dump(json_decoded,jsonFile)
Run Code Online (Sandbox Code Playgroud)
应该
with open(string_filename, 'w') as jsonFile:
json.dump(json_decoded,jsonFile)
Run Code Online (Sandbox Code Playgroud)
您可以看到我们只需要使用相同的字符串来打开一个新连接,然后我们可以根据需要为其提供用于读取文件的相同别名。我个人更喜欢 in_file 和 out_file 只是为了明确我的意图。
归档时间: |
|
查看次数: |
22925 次 |
最近记录: |