Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count empty lines in python file

Tags:

python

I would like to print the total empty lines using python. I have been trying to print using:

f = open('file.txt','r')
for line in f:
    if (line.split()) == 0:

but not able to get proper output


I have been trying to print it.. it does print the value as 0.. not sure what wrong with code..

print "\nblank lines are",(sum(line.isspace() for line in fname))

it printing as: blank lines are 0 There are 7 lines in the file. There are 46 characters in the file. There are 8 words in the file.

like image 483
shridhar kapshikar Avatar asked Jan 06 '23 15:01

shridhar kapshikar


2 Answers

Since the empty string is a falsy value, you may use .strip():

for line in f:
    if not line.strip():
        ....

The above ignores lines with only whitespaces.

If you want completely empty lines you may want to use this instead:

if line in ['\r\n', '\n']:
    ...
like image 55
Idos Avatar answered Jan 21 '23 06:01

Idos


Please use a context manager (with statement) to open files:

with open('file.txt') as f:
    print(sum(line.isspace() for line in f)) 

line.isspace() returns True (== 1) if line doesn't have any non-whitespace characters, and False (== 0) otherwise. Therefore, sum(line.isspace() for line in f) returns the number of lines that are considered empty.


line.split() always returns a list. Both

if line.split() == []:

and

if not line.split():

would work.

like image 24
vaultah Avatar answered Jan 21 '23 05:01

vaultah