Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 11, 2022 11:40 pm GMT

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)

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!


Original Link: https://dev.to/jd2r/remove-blank-lines-from-a-file-461a

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To