[Solved] Count total lines with open in Python


You are increasing your total line count incrementally with each processed line.

Read in the full file into a list, then process the list. While processing the list, increase a counter thats “the current lines nr” and pass it to the output function as well. The len() of your list is the total line count you can set to self.line_count:

def start(self):
    with open(self.usersfile, 'rt') as f:
         allLines = f.readlines()
    self.line_count = len(allLines)     
    currLine = 0
    for line in allLines:
         currLine += 1
         # do what you need to do, do not increment self.line_count
         self.check_account(username, currLine) # extend your printmethod to take the 
                                                # currLine nrand print that instead 
                                                # of self.count 
# simplified
def check_account(self,username,currLine):
    print ("{} {}/{}".format(username,currLine,self.line_count) )

4

solved Count total lines with open in Python