1

I would like to iterate through each a file, trim the whitespace for each line, and delete the line if the returned string is empty. Is there a way to avoid duplicating the .strip() call in the list comprehension below? It's not performance-critical but it feels wrong.

sub main():
    fname = "foo.txt"
    lns = []

    with open(fname, 'r') as file:
        lns = file.readlines()

    newlns = [i.strip() + "\n" for i in lns if i.strip()]
    #I want this to look like the following, which doesn't work:
    #newlns = [y + "\n" for i in lns if i.strip() as y]

    with open("out.txt", 'w') as file:
        file.writelines(newlns)
Jack Geiger
  • 115
  • 7

1 Answers1

4

You can use a nested list comprehension (well, generator expression in this case to avoid actually building a list):

newlns = [i + "\n" for i in (line.strip() for ln in lns) if i]

In fact you really shouldn't even bother to read the file first, just put it in there too: iterating over a file yields its lines.

with open(fname, 'r') as file:
    newlns = [i + "\n" for i in (line.strip() for ln in file) if i]
kindall
  • 178,883
  • 35
  • 278
  • 309