Python 类型错误:“_io.TextIOWrapper”对象不可下标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28977477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: '_io.TextIOWrapper' object is not subscriptable
提问by Eric
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.
得到标题所说的错误。这是回溯。我知道 lst[x] 导致了这个问题,但不太确定如何解决这个问题。我已经搜索了 google + stackoverflow,但没有得到我正在寻找的解决方案。
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 )
那么这个问题的解决方案是什么,或者可以做些什么来使代码工作?(代码应该做的主要功能是打开文件并获取中位数)
采纳答案by Robin Curbelo
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:
你不能索引 ( __getitem__
) 一个 _io.TextIOWrapper
对象。您可以做的是使用 alist
行。在你的代码中试试这个:
lst = open(input("Input file name: "), "r").readlines()
Also, you aren't closing the file
object, this would be better:
另外,您没有关闭file
对象,这样会更好:
with open(input("Input file name: ", "r") as lst:
print(medianStrat(lst.readlines()))
with
ensures that file get closed, see docs
with
确保文件被关闭,请参阅文档