简体   繁体   中英

How to count the number of lines that contain only one comma separated and ignore count the lines with two comma separated in text file

I want to count the number of lines that contain only one comma-separated and ignore count the lines with two comma-separated in a text file

Below is my code

def countLines(filename):
   with open(filename,'r') as f: 
      CoList = f.split("\n") 
      Counter = 0 
      for i in CoList: 
          if i: 
             Counter += 1 
      return CoList

countLines('demo.txt')

I think this is what you want?

def countLines(filename):
    with open(filename,'r') as f: 
        Counter = 0 
        for line in f: 
            if line.count(',') == 1:
                Counter += 1 
      return Counter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM