How to skip a empty line in text file using python

后端 未结 4 1586
一生所求
一生所求 2021-01-29 08:51

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| de         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-29 09:19

    You can count the size of words:

    with open("example.txt", 'r') as example_file:
        for line in example_file:
            words = line.strip().split()
            if len(words) > 3:  # line has more than three words
                if words[3] in ['book', 'pencil']:
                    print("4th word is 'book' or 'pencil'")
                elif words[3] == 'pen':
                    print("4th word is 'pen'")
    

    The output:

    4th word is 'book' or 'pencil'
    4th word is 'book' or 'pencil'
    4th word is 'pen'
    

提交回复
热议问题