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 
3
  • if not line.strip():break/return or use a try/except if it is more appropriate Commented Feb 19, 2016 at 14:46
  • 1
    If you are using a for loop, why not say if not line: continue instead of exiting the whole program? Commented Feb 19, 2016 at 14:47
  • Are you sure you want to exit if you encounter a blank line? Why not just skip blank lines? Commented Feb 19, 2016 at 14:52

2 Answers 2

1

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

if not line: raise SystemExit('No line') 
Sign up to request clarification or add additional context in comments.

6 Comments

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 thank you for that note ... just explain why it's bad approach (would delete answer )?
@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 updated line == blank thanks ..
@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.
|
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 

2 Comments

In addition, if you also want to exit if the line contains only whitespace, use if not line.strip(): sys.exit().
Why not just give the import sys in your example. "Assuming you have imported sys" doesn't really help!