只打印第一行多次

2024-09-28 21:25:50 发布

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

一个文件被传递到函数中,目标是打印行,但是它只打印第一行多次。在

def printRecord(rec1):
#read reads in a single record from the first logfile, prints it, and exits
    s = Scanner(rec1)
    line = s.readline()
    print(line)
    s.close()
    return line


def printRecords(rec1):
#loops over all records in the first log file, reading in a single record and printing it before reading in the next record
    lines = ""
    s = Scanner(rec1)
    for i in range(0, len(rec1), 1):
        lines += printRecord(rec1)
    return lines

Tags: andtheinreturndeflineitrecord
2条回答

在我看来,printRecord(rec1)只是读取文件的第一行。我可能错了,因为我用open()而不是{}。我不知道Scanner是否重要,但我会做一些类似的事情:

def printRecords(rec1):
  f = open(rec1,'r')
  lines = f.read()
  return lines

您的问题是,当您在扫描程序中关闭并重新打开日志文件时,您将从日志文件的开头开始。在

相反,取消第一个函数,只读取for循环中的行:

for i in range(0, len(rec1), 1):
    line = s.readline()
    print(line)
    lines += line
return lines

编辑

出于外交考虑,如果您想保留这两种方法,请将Scanner作为函数调用中的一个参数传入,它将跟踪它的位置。因此,与其在printRecord中创建新的扫描仪,不如:

^{pr2}$

其中s是您在printRecords中创建的扫描仪

相关问题 更多 >