with open("text.txt", 'r') as file:
for line in file:
line = line.rstrip('\n' + '').split(':')
print(line)
I am having trouble trying to remove empty lists in the series of arrays that are being generated. I want to make every line an array in text.txt
, so I would have the ability to accurately access each element individually, of each line.
The empty lists display themselves as ['']
- as you can see by the fourth line, I've tried to explicitly strip them out. The empty elements were once filled with new line characters, these were successfully removed using .rstrip('\n')
.
Edit:
I have had a misconception with some terminology, the above is now updated. Essentially, I want to get rid of empty lists.
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function. array.
There are a several ways to remove null value from list in python. we will use filter(), join() and remove() functions to delete empty string from list.
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Since I can't see your exact line, its hard to give you a solution that matches your requirements perfectly, but if you want to get all the elements in a list that are not empty strings, then you can do this:
>>> l = ["ch", '', '', 'e', '', 'e', 'se']
>>> [var for var in l if var]
Out[4]: ['ch', 'e', 'e', 'se']
You may also use filter
with None
or bool
:
>>> filter(None, l)
Out[5]: ['ch', 'e', 'e', 'se']
>>> filter(bool, l)
Out[6]: ['ch', 'e', 'e', 'se']
If you wish to get rid of lists with empty strings, then for your specific example you can do this:
with open("text.txt", 'r') as file:
for line in file:
line = line.rstrip('\n' + '').split(':')
# If line is just empty
if line != ['']:
print line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With