TypeError: '_io.TextIOWrapper' object is not subscriptable

Question:

The main function that the code should do is to open a file and get the median. This is my code:

def medianStrat(lst):
    count = 0
    test = []
    for line in lst:
        test += line.split()
        for i in lst:
            count = count +1
            if count % 2 == 0:
                x = count//2
                y = lst[x]
                z = lst[x-1]
                median = (y + z)/2
                return median
            if count %2 == 1:
                x = (count-1)//2
                return lst[x]     # Where the problem persists

def main():
    lst = open(input("Input file name: "), "r")
    print(medianStrat(lst))

Here is the error I get:

Traceback (most recent call last):
  File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 30, in <module>
    main()
  File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 28, in main
    print(medianStrat(lst))
  File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 24, in medianStrat
    return lst[x]
TypeError: '_io.TextIOWrapper' object is not subscriptable

I know lst[x] is causing this problem but not too sure how to solve this one.
So what could be the solution to this problem or what could be done instead to make the code work?

Asked By: Eric

||

Answers:

You can’t index (__getitem__) a _io.TextIOWrapper object. What you can do is work with a list of lines. Try this in your code:

lst = open(input("Input file name: "), "r").readlines()

Also, you aren’t closing the file object, this would be better:

with open(input("Input file name: ", "r") as lst:
    print(medianStrat(lst.readlines()))

with ensures that file get closed.

Answered By: Robin Curbelo

basic error my end, sharing in case anyone else finds it useful. Difference between datatypes is really important! just because it looks like JSON doesn’t mean it is JSON – I ended up on this answer, learning this the hard way.

Opening the IO Stream needs to be converted using the python json.load method, before it is a dict data type, otherwise it is still a string. Now it is in a dict it can be brought into a dataFrame.

def load_json(): # this function loads json and returns it as a dataframe
with open("1lumen.com.json", "r") as io_str:
    data = json.load(io_str)
    df = pd.DataFrame.from_dict(data)
    logging.info(df.columns.tolist())
return(df)
Answered By: James Stanbridge
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.