-2

I want to count the line only when special characters are present in the line.

count=0
with open (xvg_input, 'r') as cavity_count:
    line_to_end = cavity_count.readlines()
    for line in line_to_end:
        if "#" in line and "@" in line:
            count +=1
        print (count)    

Just want to count the lines when there is a special character.

Ron Ledger
  • 35
  • 7

2 Answers2

1

I am assuming, you want to count total number of lines where the special characters were present. If that is the case then move out the print. It is indented two levels inside.

Very slight change in your code (if all you care is to count "#" or "@", else please let us know).

count=0
with open (xvg_input, 'r') as cavity_count:
    line_to_end = cavity_count.readlines()
    for line in line_to_end:
        if "#" in line or "@" in line:
            count +=1
print(count) 

However if you instead wanted to count some other property then this method will not work. Please let us know, if this is not what you wanted.

Amit
  • 2,018
  • 1
  • 8
  • 12
0
from string import punctuation
with open(xvg_input, 'r') as cavity_count:
    print(len(
             ['' for line in cavity_count
                if any(char in line for char in punctuation)]
          ))

Or if you want to make smth with that count just save it to any var instead of printing

4xel
  • 141
  • 4