How to count certain lines in a file? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to count certain lines in a file?

There is I file and I need to count the certain lines in it, not the all lines, is there an opportunity to do it. Because the only way to count lines that I have found is: a = open("my_file.txt") count=0 for line in a: count = count +1 print (count) But it counts all lines, and when I extract the certain lines I want to count and use this code it counts only characters in one line 🤔

5th Feb 2020, 12:37 PM
Shamil Erkenov
Shamil Erkenov - avatar
1 Answer
+ 1
def count_char(text): count = 0 for c in text: count += 1 return count This is for charecter count.. So passing the line as argument gives charecters in certain line.. For line in a: print(char_count(line) Hoping it helps,.. For some info about see the text analylzer topic from this.. https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2457/
5th Feb 2020, 2:40 PM
Jayakrishna 🇮🇳