如何使用python跳过文本文件中的空行 [英] How to skip a empty line in text file using python

查看:94
本文介绍了如何使用python跳过文本文件中的空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的文本文件.

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跳过文本文件中的空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆