Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping Blank lines in read file python

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?

like image 330
Brayden Hark Avatar asked Nov 17 '16 06:11

Brayden Hark


People also ask

How do you ignore an empty line in Python?

In Python 2 use itertools. ifilter if you want a generator and in Python 3, just pass the whole thing to list if you want a list.

How do you skip a line in Python reading?

There are many ways in which you can skip a line in python. Some methods are: if, continue, break, pass, readlines(), and slicing.

How do you skip blank cell while reading a CSV file using Python?

If you want to skip all whitespace lines, you should use this test: ' '. isspace() . Beware: This method is likely to clobber files having newlines inside quoted fields. In this case the number of lines in the file is not comparable to the number of delimited records.

Are Blank lines forbidden in Python?

Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). Use blank lines in functions, sparingly, to indicate logical sections. Python accepts the control-L (i.e.


1 Answers

You can check if they are empty:

file = open('filename')
lines = [line for line in file.readlines() if line.strip()]
file.close()
like image 130
Fejs Avatar answered Oct 13 '22 00:10

Fejs