[英]TypeError: '_io.TextIOWrapper' object is not subscriptable
The main function that the code should do is to open a file and get the median.代码应该做的主要 function 是打开一个文件并获取中位数。 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.我知道
lst[x]
导致了这个问题,但不太确定如何解决这个问题。 So what could be the solution to this problem or what could be done instead to make the code work?那么这个问题的解决方案是什么,或者可以做些什么来使代码正常工作?
You can't index ( __getitem__
) a _io.TextIOWrapper
object.您不能索引 (
__getitem__
) _io.TextIOWrapper
对象。 What you can do is work with a list
of lines.您可以做的是使用行
list
。 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:另外,您没有关闭
file
对象,这样会更好:
with open(input("Input file name: ", "r") as lst:
print(medianStrat(lst.readlines()))
with
ensures that file get closed, see docs with
确保文件被关闭,请参阅文档
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.
数据类型之间的差异非常重要,仅仅因为它看起来像 JSON 并不意味着它是 JSON - 我最终得到了这个答案。 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.打开IO Stream需要使用python json.load方法进行转换,才为dict数据类型,否则还是字符串。 Now it is in a dict it can be brought into a dataFrame.
现在它在字典中,可以将其带入 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.