Is this safe? It would miss comments starting with a space. Maybe: if (line.lstrip().startswith('#'))