如何使用python跳过文本文件中的空行

编程入门 行业动态 更新时间:2024-10-25 17:23:01
本文介绍了如何使用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跳过文本文件中的空行

本文发布于:2023-05-25 10:57:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空行   如何使用   跳过   文本文件   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!