用Python打开时计算总行数

时间:2018-09-02 09:53:55

标签: python python-3.x

我想在输出中显示文件中所有行号的计数,但显示当前行号。

    guard let viewWidth = view?.frame.width else {return}

    if viewWidth < frame.width { // scaled device
        leftMargin = (frame.width - viewWidth) / 2
        rightMargin = leftMargin - viewWidth
    }

我的程序的输出在这里:

def __init__(self,file):
    self.count = 0
    self.line_count = 0

def start(self):
    with open(self.usersfile, 'rt') as f:
        for line in f.readlines():
            if not self.is_alive:break  # when the user presses Ctrl + C, self.is_alive will become False
            username = line.strip().replace('\n', '')
            self.line_count += 1
            self.check_account(username)


def check_account(self,username):
print('{}[+]Trying ({}/{}) -{}{} Username: {} Taken{}'.format(Fore.WHITE, self.count, self.line_count, Fore.RESET, Fore.RED, username, Fore.RESET))

如何在[+]Trying (1/1) - [+]Trying (2/2) - [+]Trying (3/3) - [+]Trying (4/4) - [+]Trying (5/5) - [+]Trying (6/6) - [+]Trying (7/7) - [+]Trying (8/8) - [+]Trying (9/9) - [+]Trying (10/10) - .... but i want output : [+]Trying (1/20) - [+]Trying (2/20) - [+]Trying (3/20) - [+]Trying (4/20) - [+]Trying (5/20) - [+]Trying (6/20) - 中修复它

1 个答案:

答案 0 :(得分:0)

每个处理的行都在逐步增加行总数。

将完整文件读入列表,然后处理该列表。在处理列表时,增加一个计数器,即“当前行nr”,并将其也传递给输出函数。列表中的len()是您可以设置为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) )