我有一个如下的文本文件.
I have a text file as below.
l[0]l[1]l[2]l[3]l[4]l[5]l[6] ----------------------------------- 1| abc is a book and cba too 2| xyz is a pencil and zyx too 3| def is a pen and fed too 4| aaa is实际文件是:
abc is a book and cba too xyz is a pencil and zyx too def is a pen and fed too aaa is我正在使用以下代码对该文本文件执行操作:
I'm using below code to perform operation on this text file:
import sys fr = open("example.txt",'r') for l in fr: if(l[3] is "book" or l[3] is "pencil") Then do something if(l([3] is "pen") Then do something fr.close()当我尝试执行这个程序时,我收到了类似的错误
When I'm trying to execute this program I'm getting error like
Traceback(most recent call last): File "abc.py" line 4 in <module> if(l[3] is "book" or l[3] is "pencil"): IndexError: list index error out of range因为根据上面最后一行(即第 4 行)的文本文件,l[3] 处没有任何内容
Because as per the above text file in last line(i.e line 4) there is nothing at l[3]
l[0] l[1] l[2] l[3] l[4] l[5] l[6]aaa是
l[0] l[1] l[2] l[3] l[4] l[5] l[6] aaa is
这里的第 4 行 l[3] 是空的.所以我的问题是如何在 l[3] 为空时跳过这一行?我们可以像下面这样吗
Here in 4th line l[3] is empty. So my question is how to skip this line when l[3] is empty ? Can we campare like below
if(l[3] ==""): continue请有人在这里帮助我.
推荐答案您可以在 for 循环开始时验证列表长度,然后 continue 如果有没有第三个元素:
You can verify the list length at the beginning of your for loop and then continue if there is no 3rd element:
if len(l)<3:继续
附注.当然,你必须先l.split()这一行,否则你只能访问单个字符.
PS. Of course, you have to l.split() the line first, otherwise you will access single characters only.
更多推荐
如何使用python跳过文本文件中的空行
发布评论