【问题标题】:Count total lines with open in Python计算在 Python 中打开的总行数
【发布时间】:2018-09-02 09:53:54
【问题描述】:

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

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) -

如何在with open(self.usersfile, 'rt') as f: 中修复它

【问题讨论】:

  • 您缺少大部分class 定义,self.usersfile 未指定,line.strip().replace('\n', '') 中的replace 被浪费了,因为strip() 已经在末尾摆脱了\n -在line 内不能有\n,因为那样它将是一个单独的行......除此之外 - 你的缩进需要认真修复才能使这个有效的代码。请解决问题,以便我们有一个minimal verifyable complete example 与您合作并为您提供帮助。

标签: python python-3.x


【解决方案1】:

随着每条已处理的行逐渐增加总行数。

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

【讨论】:

  • 我得到了 alueError: I/O operation on closed file。错误。
  • @Mehran 您已经从文件中读取了所有数据。它在allLines 内部——不再对文件进行操作,只对allLines 列表进行操作和使用。
  • for line in allLines(): TypeError: 'list' object is not callable
  • @Mehran for line in allLines() 不在此示例代码中。您自己添加了(),使其成为函数调用
猜你喜欢
  • 1970-01-01
  • 2023-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多