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" 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')
CodePudding user response:
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
.
CodePudding user response:
You could use regex for searching patterns
import re
with open('somefile.txt','r') as file:
txt = file.readlines()for i in txt:
if re.fullmatch("\\s*",i):
continue
print(i,end="")
but you could do it with pure python too
with open('somefile.txt','r') as file:
txt = file.readlines()
for i in txt:
if i.strip() == '':
continue
print(i, end='')