首页 > 解决方案 > Python:尝试使用我打开的文件的内容时出现 TypeError

问题描述

我真的是 python 或一般编程的新手,在过去的几个小时里我遇到了这个问题,我显然很糟糕地弄清楚出了什么问题。

def read_file(input_filename):
    file_list = []
    with open(input_filename, 'r') as open_file:
        for x in range(len(open_file)):
            print(open_file[x] +  " [" + str(x) + "]")
            if (x % 2) == 0:
                thisTuple = (open_file[x], open_file[x + 1])
                file_list.append(thisTuple)

我希望我能给予比感谢更多的帮助作为回报,但如果有人能给我任何关于我可能做错了什么的指示,那真的意义重大。

谢谢!

标签: pythontypeerror

解决方案


您收到错误的原因是由于以下语句:

for x in range(len(open_file)):

open_file没有实现__len__Python 魔术函数。它也不是可下标的对象(如字符串)。它是一个TextIOWrapper. 如果要将数据作为字符串获取,则需要调用open_file.read()

data= open_file.read()
for x in range(len(data)):
    print(data[x] +  " [" + str(x) + "]")
    if (x % 2) == 0:
        thisTuple = (data[x], data[x + 1])
        file_list.append(thisTuple)

推荐阅读