How can I get the count of line in a file with different character

66 Views Asked by At

In the txt file it is composed of the following writing:

funded_txo_count:0 funded_txo_count:0 funded_txo_count:5

I use this code to count number of specific string or character example, if I have "0" 1000 times, the output if 1000,

But what do I have to do to identify the different lines that do not contain this string or character? I mean the number of the line itself, since the txt file that I want to identify is based on each line

d = 0
with open("filename.txt", "r") as in_file:
    for line in in_file:
        d += line.count("0")

print(d)

Output: 2

I want to identify the other lines that do not contain the character or string 0

Identifying different characters according to the line.

3

There are 3 best solutions below

0
John Gordon On

Add some code to keep track of the current line number. Also when you call count(), add a bit of extra processing if it did not find anything:

with open("filename.txt", "r") as in_file:
    line_number = 0
    for line in in_file:
        line_number += 1
        zero_count = line.count("0")
        if zero_count == 0:
            print(f"line {line_number} does not contain 0")
        d += zero_count
0
STK On

I hope I understood you correctly, but what you can do is this

You can get the total number of lines that the file has, and substitute from it the number of lines that have "0"

with open(r"filename.txt", 'r') as fp:
    d = 0
    lines = len(fp.readlines())
    
    for line in fp:
        d += line.count("0")

print(d)
print(f"The number of lines without 0 is ${lines-d}")
0
tdelaney On

You can use not in for a simple test of the character "0" in a line. Use enumerate to iterate file lines with a line count and put it all in a list comprehension.

line_nums = [line_num
    for line_num, line in enumerate(open("filename.txt"), 1)
    if "0" not in line]