An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
December 11, 2022 11:40 pm GMT
Original Link: https://dev.to/jd2r/remove-blank-lines-from-a-file-461a
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To