Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 911
A T Avatar asked Nov 07 '18 22:11

A T


1 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.

like image 116
General4077 Avatar answered Oct 13 '22 00:10

General4077