DEV Community

DR
DR

Posted on

3 1

Remove Blank Lines from a File with Python

Hi everyone! After fighting with syntax errors for the last ten minutes, I've finally figured out an elegant one-liner that removes all blank lines from a Python file.

with open('your_file.txt') as file:
  lines = list(filter(lambda l: l.strip(), file.readlines()))
  for line in lines:
    print(line)
Enter fullscreen mode Exit fullscreen mode

I had already been told that the strip() method was the way to go when determining blank lines, so I simply incorporated it into a lambda function. Best part in my opinion - it doesn't mutate the original file because it uses filter.

Make sure to follow for more interesting JS/Python tidbits!

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay