質問

A file is passed into the functions and the goal is to print line, however it is only printing the first line multiple times.

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
役に立ちましたか?

解決

Your trouble is that when you close and reopen the log file in the Scanner you start from the beginning of the log file.

Instead, do away with the first function and just read lines in the for loop:

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

EDIT

By way of being diplomatic, if you wanted to keep both methods, pass the Scanner in as a parameter in the function call and it will keep track of where it is. So instead of creating a new Scanner in printRecord, instead:

def printRecord(rec1, s):

where s is the Scanner you created in printRecords

他のヒント

It looks to me like printRecord(rec1) is simply reading the first line of the file. I may be wrong as I use open() instead of Scanner(). I don't know if Scanner is important, but I would make something like:

def printRecords(rec1):
  f = open(rec1,'r')
  lines = f.read()
  return lines
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top