+2 votes
in Programming Languages by (73.8k points)
I am reading a very large file where some of the records are empty. Because of those records, my code gives error. How can I check if the record is an empty record?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

There can be several ways to check an empty line. You can try one of these three ways:

if len(line.strip()) == 0 :
 # do something

if line.strip() == '':
 # do something
 
if not line.strip():
 # do something

Example:

>>> line ='aa'
>>> len(line.strip()) == 0
False
>>> line.strip() == ''
False
>>> line.strip()
'aa'
>>> not line.strip()
False
>>> line = ''
>>> not line.strip()
True
>>> line.strip() == ''
True
>>> len(line.strip()) == 0
True


...