You can use a generator to read all the lines and strip()
the unwanted newlines.
From the generator you only use those elements that are "Truthy" - empty strings are considered False
.
Advantage: you create only one list and get rid of empty strings:
Write file:
filename = "t.txt"
with open(filename,"w") as f:
f.write("""
c
oo
l
te
xt
""")
Process file:
with open(filename) as f:
testo = [x for x in (line.strip() for line in f) if x] # f.readlines() not needed. f is
# an iterable in its own right
print(testo) # ['c', 'oo', 'l', 'te', 'xt']
You could do the similarly:
testo = [line.strip() for line in f if line.strip()]
but that would execute strip()
twice and would be slightly less efficient.
Output:
['c', 'oo', 'l', 'te', 'xt']
Doku:
A suggested alternative from Eli Korvigo is:
testo = list(filter(bool, map(str.strip, f)))
with is essentially the same - replacing the explicit list comp using a generator comp with a map
of str.strip
on f
(resulting in a generator) and applying a filter
to that to feed it into a list.
See built in function for the docu of filter,map,bool
.
I like mine better though ;o)