TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

杀马特。学长 韩版系。学妹 提交于 2020-06-27 14:40:09

问题


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

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

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.


回答1:


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

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.

To answer the question though:

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

should be

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

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.



来源:https://stackoverflow.com/questions/53198665/typeerror-expected-str-bytes-or-os-pathlike-object-not-io-textiowrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!