TypeError: object '_io.TextIOWrapper' cannot be decrypted

Getting an error in the header. Here is the trace. I know that lst [x] is causing this problem, but not too sure how to solve this problem. I already searched google + stackoverflow, but did not get the solution I'm looking for.

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 

Here is the actual 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)) 

So what can be the solution to this problem or what can be done to get the code to work? (The main function that the code should perform is to open the file and get the median)

+5
source share
1 answer

You cannot index ( __getitem__ ) the _io.TextIOWrapper object. What you can do is work with list strings. Try this in your code:

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

In addition, you do not close the file object, this would be better:

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

with ensures the file is closed, see docs

+4
source

Source: https://habr.com/ru/post/1215104/


All Articles