1

My file is a .txt file and all comments have no spaces before them.

I have a file with 10,000 lines that looks like this and I am reading every line of the file.

## something
## something
## something
12312312
123123
12312312
123123
123123

However, my code will fail if there is not a value in every line.

Is there a way in Python to exit the program if the line is blank?

I just need a simple If statement to fix my program.

Something like

if line == blank:
    quit

2 Answers2

1

If you want to completely exit the program and the line contains no whitespace(if it does replace line with line.strip():

import sys

if not line:
    sys.exit() 

As pointed out by @zondo, you could just use a continue statement to skip that line if you do not want the program to fail:

if not line.strip():
    continue
Michael Harley
  • 831
  • 1
  • 9
  • 20
M.T
  • 4,917
  • 4
  • 33
  • 52
  • 2
    In addition, if you also want to exit if the line contains only whitespace, use `if not line.strip(): sys.exit()`. – timgeb Feb 19 '16 at 14:49
  • Why not just give the `import sys` in your example. "Assuming you have imported sys" doesn't really help! – Michael Harley Oct 25 '20 at 02:43
1

You could ommit importing sys to run sys.exit() and raise SystemExit exception instead:

if not line:
     raise SystemExit('No line')
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • 1
    That is not the preferred way to exit a program. `sys.exit()` is the preferred way; `exit()` is an accepted way, but `raise SystemExit` is not. – zondo Feb 19 '16 at 14:49
  • @zondo thank you for that note ... just explain why it's bad approach (would delete answer )? – Andriy Ivaneyko Feb 19 '16 at 14:49
  • @zondo sys.exit() just raises SystemExit, why do you think this is a bad way to exit as opposed to using the sys module? Do you have any sources? The problem with this answer is the `line == blank` check, not the way the exit is done. – timgeb Feb 19 '16 at 14:50
  • @timgeb updated `line == blank` thanks .. – Andriy Ivaneyko Feb 19 '16 at 14:52
  • 1
    @timgeb: I withdraw partially my comment. I have just done a bit of researching and have discovered that you are correct: `sys.exit()` just raises `SystemExit`. I do still believe that `sys.exit()` is preferable, though, because future versions of Python may change its implementation to more than just raising an exception. Since that is merely an opinion, I have removed my downvote. – zondo Feb 19 '16 at 15:00
  • @zondo fair enough :) – timgeb Feb 19 '16 at 15:02