How to remove empty lines with re?

Peter Otten __peter__ at web.de
Fri Oct 10 04:59:27 EDT 2003


ted wrote:

> I'm having trouble using the re module to remove empty lines in a file.
> 
> Here's what I thought would work, but it doesn't:
> 
> import re
> f = open("old_site/index.html")
> for line in f:
>     line = re.sub(r'^\s+$|\n', '', line)
>     print line

Try:

import sys
for line in f:
    if line.strip():
        sys.stdout.write(line)

Background: lines read from the file keep their trailing "\n", a second
newline is inserted by the print statement.
The strip() method creates a copy of the string with all leading/trailing
whitespace chars removed. All but the empty string evaluate to True in the
if statement.

Peter




More information about the Python-list mailing list