Skipping Blank lines in read file python

Brayden Hark picture Brayden Hark · Nov 17, 2016 · Viewed 32.1k times · Source

Im working on a very long project, i have everything done with it, but in the file he wants us to read at the bottom there are empty spaces, legit just blank spaces that we aren't allowed to delete, to work on the project i deleted them because i have no idea how to get around it, so my current open/read looks like this

      file = open("C:\\Users\\bh1337\\Documents\\2015HomicideLog_FINAL.txt" , "r")
 lines=file.readlines()[1:]
 file.close()

What do i need to add to this to ignore blank lines? or to stop when it gets to a blank line?

Answer

Fejs picture Fejs · Nov 17, 2016

You can check if they are empty:

file = open('filename')
lines = [line for line in file.readlines() if line.strip()]
file.close()