[SOLVED] How to delete ’empty’ lines in txt file

Issue

This Content is from Stack Overflow. Question asked by Dominik Grześkowiak

I think I’ve tried everything to make it work but I still can’t get the results I want. I basically want to delete empty lines in txt file that my other script created. I’ve tried: .isspace(), deleting lines with n amount of spaces, deleting lines with ‘n’. None of these worked can you guys help me? Here is part of txt file and my code:

Gmina Wiejska
 Urząd Gminy Brzeziny 
 

 

 ul. Sienkiewicza 16a 95-060 Brzeziny
Łącko
Gmina Wiejska
 Urząd Gminy Łącko 


Łącko 445 33-390 Łącko
Węgliniec
Gmina Miejsko-wiejska
 Urząd Gminy i Miasta Węgliniec 


ul. Sikorskiego 3 59-940 Węgliniec```

code:

delete = ['<td align="center" class="top" colspan="3"><b>',
          '</td>',
          '<br/></b></td>',
          '<br/></b>',
          'None',
          'brak',
          '[]',
          'n'
          ]
with open('/Users/dominikgrzeskowiak/python/gminy/text/text1.txt','r+') as file:
    for line in file:
        print(a)
        for i in delete:
            line = line.replace(i,'')
            print(i)
        print(line)  
        if line != '  ' or line != ' n' or line != '   ':  
            with open('/Users/dominikgrzeskowiak/python/gminy/text/text2.txt','a') as f:
                f.write(line+'n')



Solution

Just check if the line is not empty after removing blanks with strip

with open('text1.txt', 'r+', encoding='utf-8') as file, open('text2.txt', 'a', encoding='utf-8') as f:
    for line in file:
        if line.strip():
            f.write(line)

You should open text2 once, not every line in the text1.


This Question was asked in StackOverflow by Dominik Grześkowiak and Answered by Guy It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?