The empty strings (''
) are what's left over if you strip
something that's all whitespace (or possibly they were empty to start with). The easiest way to eliminate these is to use the fact that ''
is falsy, so you can remove them right there in your list comprehensions by adding if item.strip()
.
The problem is that you're iterating over the output of file.read()
, which is a single string. Strings in Python are iterable, but this means that when you iterate over them, you iterate over each character. So what you're doing is stripping each individual character and adding it to your list--so all your newlines turn into empty strings, rather than being stripped out like I think you intended.
To fix it, use the fact that file objects are also iterable, and iterate line-by-line. This is the idiomatic way to read a file line-by-line in Python (using a context manager rather than a lone open
call):
with open('single.dat') as f:
for line in f:
dosomething(line)
So, use that pattern along with some filtering in your list comprehension, and you'll be all set:
with open('single.dat') as f:
single = [line.strip() for line in f if line.strip()]