Home
Go
Get File Lines Example
Updated Dec 29, 2024
Dot Net Perls
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 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.
File
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.
for
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.
Review. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 29, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen