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(), fi…


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.


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Remove Blank Lines from a File with Python." Dominic R. | Sciencx - Sunday December 11, 2022, https://www.scien.cx/2022/12/11/remove-blank-lines-from-a-file-with-python/
HARVARD
Dominic R. | Sciencx Sunday December 11, 2022 » Remove Blank Lines from a File with Python., viewed ,<https://www.scien.cx/2022/12/11/remove-blank-lines-from-a-file-with-python/>
VANCOUVER
Dominic R. | Sciencx - » Remove Blank Lines from a File with Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/12/11/remove-blank-lines-from-a-file-with-python/
CHICAGO
" » Remove Blank Lines from a File with Python." Dominic R. | Sciencx - Accessed . https://www.scien.cx/2022/12/11/remove-blank-lines-from-a-file-with-python/
IEEE
" » Remove Blank Lines from a File with Python." Dominic R. | Sciencx [Online]. Available: https://www.scien.cx/2022/12/11/remove-blank-lines-from-a-file-with-python/. [Accessed: ]
rf:citation
» Remove Blank Lines from a File with Python | Dominic R. | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.