Get lines, file. 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 Golang, 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.
An example. 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.
Start We open a file, create a NewScanner with bufio, and call Scan in a loop. The Text func returns each line.
Info This method returns the line stripped of whitespace on the start and end. So we do not need to deal with newlines ourselves.
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 loop. Look 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.
Note, loop. 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.
Tip The file contains the lines "Thank you" and then "Friend." So it is a friendly file at least.
A review. The LinesInFile method is useful for iterating over the lines in a text file in Golang in an efficient way. It handles common forms of newlines well.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 22, 2023 (edit).