TypeError:预期的str,字节或os.PathLike对象,而不是_io.TextIOWrapper [英] TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

查看:679
本文介绍了TypeError:预期的str,字节或os.PathLike对象,而不是_io.TextIOWrapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to open, read, modify, and close a json file using the example here:

如何在使用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文件名.

I keep getting an error at the end (with open(jsonFile...) that I can't use the jsonFile variable with open(). I used the exact format as the example provided in the link above so I'm not sure why it's not working. This is eventually going in a larger script so I want to stay away from hard coding/ using strings for the json file name.

推荐答案

这个问题有点老了,但是对于有同样问题的任何人:

This Question is a bit old, but for anyone with the same issue:

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

You're right you can't open the jsonFile variable. Its a pointer to another file connection and open wants a string or something similar. Its worth noting that jsonFile should also be closed once you exit the 'with' block so it should not be referenced outside of that.

但是要回答这个问题:

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只是为了明确我的意图.

You can see we just need to use the same string to open a new connection and then we can give it the same alias we used to read the file if we want. Personally I prefer in_file and out_file just to be explicit about my intent.

这篇关于TypeError:预期的str,字节或os.PathLike对象,而不是_io.TextIOWrapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆