For example if my text file is:
blue
green
yellow
black
Here there are four lines and now I want to get the result as four. How can I do th
You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.
with open('text.txt') as myfile:
count = sum(1 for line in myfile)
It seems by what you have tried that you don't want to include empty lines. You can then do:
with open('text.txt') as myfile:
count = sum(1 for line in myfile if line.rstrip('\n'))