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.
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']:
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With