I'm having some troubles with removing items from a list. I'm looking for a more elegant solution. Preferably a solution in one for-loop or filter.
The objective of the piece of code: remove all empty entries and all entries starting with a '#' from the config handle.
At the moment i'm using:
# Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle
This works but I think it is a bit of a nasty solution.
When I try:
# Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items and empty items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
elif len(item) == 0:
configHandle.remove(item)
This, however, fails. I cannot figure out why.
Can someone push me in the right direction?