[英]Text reading and list index out of range in Python
I have a text that has 8 rows. 我的文本有8行。 The program will read this text and match the word in the text with the word that user enters.
程序将读取此文本,并将文本中的单词与用户输入的单词进行匹配。 But python gives a mistake:
但是python给出了一个错误:
satir=dosya.readlines()[a]
IndexError: list index out of range
This is my code: 这是我的代码:
a=0
c=0
while a<8:
satir=dosya.readlines()[a]
a=a+1
for i in olasilik:
if ((olasilik[c]+"\n")==satir):
c=c+1
print(olasilik[c])
this is not how you should do it 这不是你应该怎么做
instead do 代替做
for satir in dosya:
#do something
The problem is that readlines()
reads all the content of the file in a list the first time you call it. 问题是,当您第一次调用
readlines()
,它将读取列表中文件的所有内容。 The second time you call it the file is already finished and you get an empty list and you get an error trying to access element 1
of that empty list. 第二次调用该文件时,文件已经完成,您得到一个空列表,并且在尝试访问该空列表的元素
1
时遇到错误。
To loop over the lines of the file you can do 要遍历文件的行,您可以执行
for L in f:
...
or 要么
for L in f.readlines():
...
This would probably work better: 这可能会更好地工作:
for satir in dosya.readlines():
for o in olasilik:
if ("%s\n" % o) == satir:
print o
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.