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

2024-02-28

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

  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

我使用下面的代码对此文本文件执行操作:

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()

当我尝试执行这个程序时,我收到如下错误

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] 处没有任何内容

l[0] l[1] l[2] l[3] l[4] l[5] l[6]
AAA 是

第 4 行 l[3] 为空。 所以我的问题是当 l[3] 为空时如何跳过这一行? 我们可以像下面这样露营吗

if(l[3] ==""):
     continue

请有人在这里帮助我。


您可以检查单词数组的长度。

但请注意,当您直接索引时l,您将进入字符级别,而不是您似乎想要的单词级别。另外,我会用==代替is.

做这样的事情:

with open("a.txt", 'r') as fr:
    for l in fr:
        words = l.split()
        if len(words) < 3:
            continue
        if words[3] == "book" or words[3] == "pencil":
            print("Book or pencil")
        elif words[3] == "pen":
            print("Pen")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐