+2 votes
in Programming Languages by (7.9k 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

0 votes
by (15.3k points)

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

...