TypeError: '_io.TextIOWrapper' object is not subscriptable in Python
Dung Do Tien
Sep 13 2021
193
Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have a small assignment, I want to read file and analystic data of it. Like this:
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))
main()
But I get an exception TypeError: '_io.TextIOWrapper' object is not subscriptable when I run code above.
Traceback (most recent call last):
File "C:/Users/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 30, in <module>
main()
File "C:/Users/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 28, in main
print(medianStrat(lst))
File "C:/Users/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 24, in medianStrat
return lst[x]
TypeError: '_io.TextIOWrapper' object is not subscriptable
And I am using python 3.8.2
Anyone can explain it to me? How can I solve it?
Thanks for any response.
Have 1 answer(s) found.
-
M-3
Manish Kumar Sep 13 2021
You can try change:
lst = open(input("Input file name: "), "r")
To
lst = open(input("Input file name: "), "r").readlines()
Also, you are not closing the object
file
, it would be better because it sure that file is closed:with open(input("Input file name: ", "r") as lst: print(medianStrat(lst.readlines()))
I hope it helpful for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.