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.

2

2 Answers

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.

0

If you come here because you are reading in a file from the command line using click and the file cannot be opened/read by with open(click_file_obj, "r") as f, use the name attribute of the _texIOwrapper object generated by click. That is,

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

This worked for me. Source:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.