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

Answers


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

Need Your Help

MySQL Recursive Get Right Nodes PHP

php mysql binary-tree

I have a table containing user id with left node and right node (Both are which user id). I am trying to create a function to count all the right nodes and total nodes of a particular user id in PH...

Google Maps for Android - Polyline crashing app

java android json google-maps geojson

I am importing geoJSON data from .jsons files. It works very well with some files but not with others. I thought my files had problems but I tested them on geojson lint as well as geojson.io without