This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Dominic R.
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!
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Dominic R.
Dominic R. | Sciencx (2022-12-11T23:40:06+00:00) Remove Blank Lines from a File with Python. Retrieved from https://www.scien.cx/2022/12/11/remove-blank-lines-from-a-file-with-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.