【发布时间】:2022-01-14 09:50:07
【问题描述】:
我正在尝试编写一个代码,它将电影存储在一个列表中,我可以通过要求按位置添加电影或检查它是否在列表中来检索该列表。到目前为止,我一直在研究检索部分,但我不断收到错误消息,其中“'list' 对象的描述符'index' 不适用于'str' 对象”。 这是我目前的代码
myFile = open("movies.txt", "a")
more = "yes"
while more.lower() == "yes":
movie = input("Please enter a movie title: ")
myFile.write(movie + '\n')
more = input("Would you like another item? Enter 'yes' or 'no'. ")
find = input("Would you like to find a movie? Enter 'yes' or 'no'. ")
myFile.close()
if find == "yes":
myFile = open("movies.txt")
xlist = list[myFile]
f2 = input("What movie would like to find?")
f3 = xlist.index(f2)
print(f2 + " is in number " + f3 + " on the list")
【问题讨论】:
-
list[myFile]- 这并没有你认为的那样 -
这能回答你的问题吗? How to read a file line-by-line into a list?
-
使用 myFile.readlines() 逐行读取文件而不是 list[myFile]
-
现在问题是输出是:'str'对象没有属性'restrip'。刚刚尝试了 readlines() 但它只是说我的值(随机 a)不在列表中
-
rstrip,而不是restrip。 r 代表右,l 代表左。