4
votes

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?

4
line can have spaces or tabs and loooks like empty. - furas
use for line in file: if not line.strip(): print("it is empty line") - furas
Pretty sure an empty list has a False boolean value. - Right leg

4 Answers

7
votes

You can check if they are empty:

file = open('filename')
lines = [line for line in file.readlines() if line.strip()]
file.close()
6
votes
for line in file:
  if not line.strip():
    ... do something

Follwoing will be best for readinf files

with open("fname.txt") as file:
    for line in file:
      if not line.strip():
        ... do something

With open will takecare of file close.

If you want to ignore lines with only whitespace

3
votes

Here's a very simple way to skip the empty lines:

with open(file) as f_in: 
    lines = list(line for line in (l.strip() for l in f_in) if line)
2
votes
  1. One way is to use the lines list and remove all the elements e such that e.strip() is empty. This way, you can delete all lines with just whitespaces.
  2. Other way is to use f.readline instead of f.readlines() which will read the file line by line. First, initialize an empty list. If the present read-in line, after stripping, is empty, ignore that line and continue to read the next line. Else add the read-in line to the list.

Hope this helps!