简体   繁体   中英

Only printing the first line multiple times

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM