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


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
Gmina Wiejska
 Urząd Gminy Łącko 

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

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


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


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

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?