let's have file following content(every line blank):
line 1
line 2
line 3
...
i tried read file in 2 ways:
count = 0 line in open("myfile.txt"): if line == '': #or if len(line) == 0 count += 1
and
count = 0 file = open('myfile.txt') lines = file.readlines() line in lines: if line == '': #or if len(line) == 0 count += 1
but count
remains 0. how can count number of blank lines?
in more simple , pythonic way:
with open(filename) fd: count = sum(1 line in fd if len(line.strip()) == 0)
this keep linear complexity in time , constant complexity in memory. and, of all, rid of variable count
manually incremented variable.
Comments
Post a Comment