I'm working on a file text, but, as it has spaces at the beginning too, when I try to delete my \n
using the strip
mode and list
comprehension, I get a list with empty elements (" ")
and I don't know how to delete them.
I have a text and my code is:
with open(filename) as f:
testo= f.readlines()
[e.strip() for e in testo]
but I get a list like this:
[' ', ' ', 'word1', 'word2', 'word3', ' ']
I wanted to know if I can work it out with the strip
method, otherwise with another method.
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)