python - 代码未读取文件,错误对象 Len() MASTERLIST

标签 python

这是我第一次在这里发帖。我正在做一项作业,但我遇到了困难。

Here is what my professor is asking for - click to see the screenshot

这是我的代码:

option1=open("BrandVB.txt", "r")
option2=open("BrandA.txt", "r")
option3=open("BrandC.txt", "r")
option4=open("BrandX.txt", "r")

#Creating a master lits
li = [option1, option2,option3, option4]

#Searching part numbers based on brand
brand=input("Enter the brand: ")
for i in range(len(li)):
    for j in range(len(li[i])):
        if brand==li[i][j]:
            pos=j
for i in range(len(li)):
    print(li[i][pos])

我得到的错误是:

Traceback (most recent call last):
  File "/Users/admin/Desktop/Desktop/LAB10/LAB10.py", line 17, in <module>
    for j in range(len(li[i])):
TypeError: object of type '_io.TextIOWrapper' has no len()

最佳答案

仅仅打开文件是不够的,您还需要从中.read()。这是一种方法:

with open("BrandVB.txt", "r") as a, open("BrandA.txt", "r") as b, open("BrandC.txt", "r") as c, open("BrandX.txt", "r") as d:
    option1 = a.read()
    option2 = b.read()
    option3 = c.read()
    option4 = d.read()
<小时/>

Python - Reading and Writing Files

关于python - 代码未读取文件,错误对象 Len() MASTERLIST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53607167/

相关文章:

python - 在 Python 中检测 NUMLOCK/CAPSLOCK/SCRLOCK keypress/keyup

python - pygame `.mid` 音频文件在其他平台上听起来不同

python - 一个Python函数,它需要多少行和多少列,以网格形式打印一对空方括号[]

python - 如何: django template pass array and use it in javascript?

python - 在 python 中创建一个圆形条形图

python - python的开放高度api

python - 如何返回 Python 数组中目标元素的索引?

python - 使用 wxPython 配置 Eclipse

python - 从父函数获取变量

python - 如何过滤或选择 pandas 列中仅包含日期的行