What is the most pythonic way to read in a named file, strip lines that are either empty, contain only spaces, or have # as a first character, and then process remaining lines? Assume it all fits easily in memory.
Note: it’s not tough to do this — what I’m asking is for the most pythonic way. I’ve been writing a lot of Ruby and Java and have lost my feel.
Here’s a strawman:
file_lines = [line.strip() for line in open(config_file, 'r').readlines() if len(line.strip()) > 0]
for line in file_lines:
if line[0] == '#':
continue
# Do whatever with line here.
I’m interested in concision, but not at the cost of becoming hard to read.
The
.isspace()method of strings is by far the best way to test if a string is entirely whitespace — no need for contortions such aslen(r.strip()) == 0(ech;-).