Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - TypeError: '_io.TextIOWrapper' object is not subscriptable

Getting the error as the title says. Here is the traceback. I know lst[x] is causing this problem but not too sure how to solve this one. I've searched google + stackoverflow already but did not get the solution I am 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 could be the solution to this problem or what could be done instead to make the code work? ( The main function that the code should do is to open a file and get the median )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, see docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...