更新Python for循环中的迭代值

2024-06-25 06:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

对Python很陌生,并且编写了一个脚本来挑选基本日志文件的某些行

基本上,该函数搜索文件的行,当它找到一个要输出到单独文件的行时,将其添加到一个列表中,然后再添加后面的五行。然后在另一个函数的末尾将输出到一个单独的文件。

接下来我要做的就是从这五行中的最后一行跳下去,而不是再重复一遍。我以为代码的最后一行可以解决问题,但不幸的是没有。

是否有任何推荐的for循环变体可以用于此目的?

def readSingleDayLogs(aDir): 
print 'Processing files in ' + str(aDir)    + '\n'
lineNumber = 0
try:
    open_aDirFile = open(aDir)  #open the log file
    for aLine in open_aDirFile: #total the num. lines in file
        lineNumber = lineNumber + 1
    lowerBound = 0
    for lineIDX in range(lowerBound, lineNumber):          
        currentLine = linecache.getline(aDir, lineIDX)
        if (bunch of logic conditions):
                    issueList.append(currentLine)
                    for extraLineIDX in range(1, 6): #loop over the next five lines of the error and append to issue list
                        extraLine = linecache.getline(aDir, lineIDX+ extraLineIDX) #get the x extra line after problem line
                        issueList.append(extraLine)
                    issueList.append('\n\n')
                    lowerBound = lineIDX

Tags: 文件the函数inforopenfilelines
3条回答

for循环在范围内使用迭代器,因此您可以更改循环变量。

考虑改用while循环。这样,就可以直接更新行索引。

您应该使用while循环:

line = lowerBound
while line < lineNumber:
    ...
    if conditions:
        ...
        for lineIDX in range(line, line+6):
           ...
        line = line + 6
    else:
        line = line + 1

我会看这样的东西:

from itertools import islice

with open('somefile') as fin:
    line_count = 0
    my_lines = []
    for line in fin:
        line_count += 1
        if some_logic(line):
            my_lines.append(line)
            next_5 = list(islice(fin, 5))
            line_count += len(next_5)
            my_lines.extend(next_5)

这样,通过对输入使用islice,您可以将迭代器向前移动,并在5行(如果接近文件末尾,可能更少)用完后继续。

这是基于如果我理解正确,您可以通过文件向前读取,标识一行,并且只希望在该点之后有固定数量的行,然后按照正常情况恢复循环。(如果这就是您所追求的全部,您甚至可能不需要行计数,因为它看起来只是为了getline而不是任何其他目的)。

如果您确实想使用下一个5,并且仍然考虑下一行,则可以使用itertools.tee在故障行的点处分支,然后islice在下一行继续使用fin迭代器。

相关问题 更多 >