TypeError:需要 str、bytes 或 os.PathLike 对象,而不是 _io.TextIOWrapper

问题描述 投票:0回答:3

我正在尝试使用此处的示例打开、读取、修改和关闭 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

我在最后不断收到错误(

open(jsonFile...)
),我不能将
jsonFile
变量与
open()
一起使用。我使用了上面链接中提供的示例的确切格式,所以我不确定为什么它不起作用。这最终会出现在一个更大的脚本中,所以我想远离硬编码/使用字符串作为 json 文件名。

python json file contextmanager
3个回答
11
投票

这个问题有点老了,但对于有同样问题的人来说:

你是对的,你无法打开 jsonFile 变量。它是指向另一个文件连接的指针,并且打开需要一个字符串或类似的东西。值得注意的是,一旦退出“with”块,jsonFile 也应该关闭,因此不应在该块之外引用它。

回答这个问题:

with open(jsonFile, 'w') as jsonFile:
   json.dump(json_decoded,jsonFile)

应该是

with open(string_filename, 'w') as jsonFile:
    json.dump(json_decoded,jsonFile)

您可以看到我们只需要使用相同的字符串来打开一个新连接,然后我们可以根据需要为其指定用于读取文件的相同别名。就我个人而言,我更喜欢 in_file 和 out_file 只是为了明确我的意图。


1
投票

如果您来到这里是因为您正在使用 click 从命令行读取文件,并且该文件无法通过

with open(click_file_obj, "r") as f
打开/读取,请使用由 click 生成的 _texIOwrapper 对象的
name
属性。也就是说,

with open(click_file_obj.name, "r") as f:
    file_text = f.read()

这对我有用。 来源:https://python-forum.io/thread-1277.html


0
投票

如果您的问题仍未解决,我建议检查此网站:预期的 str、字节或 os.PathLike 对象,而不是 TextIOWrapper

© www.soinside.com 2019 - 2024. All rights reserved.