For file processing, we often need to get each line in a file. We can store the lines in a string
slice, or process each one as we encounter it.
In Go, the Scanner type (returned by bufio.NewScanner
) is helpful here. We can use append()
to build up our string
slice of file lines. The code can be placed in a separate method.
To begin, please notice how we have imported the "bufio" and "os" packages. These are used in LinesInFile
, our most important method in the example.
NewScanner
with bufio, and call Scan
in a loop. The Text func
returns each line.package main import ( "bufio" "fmt" "os" ) func LinesInFile(fileName string) []string { f, _ := os.Open(fileName) // Create new Scanner. scanner := bufio.NewScanner(f) result := []string{} // Use Scan. for scanner.Scan() { line := scanner.Text() // Append line to result. result = append(result, line) } return result } func main() { // Loop over lines in file. for index, line := range LinesInFile(`C:\programs\file.txt`) { fmt.Printf("Index = %v, line = %v\n", index , line) } // Get count of lines. lines := LinesInFile(`C:\programs\file.txt`) fmt.Println(len(lines)) }Index = 0, line = Thank you Index = 1, line = Friend 2
For
-range loopLook carefully at the for
-loop in the main method. We receive 2 values for each iteration—the index and the string
itself. These can be used in the loop body.
The LinesInFile
func
is invoked only once for the entire loop. So the file is only opened once. We do not need to worry about excess IO or allocations.
The LinesInFile
method is useful for iterating over the lines in a text file in Go in an efficient way. It handles common forms of newlines well.