C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
LinesInFile: We open a file, create a NewScanner with bufio, and call Scan in a loop. The Text func returns each line.
Text: This method returns the line stripped of whitespace on the start and end. So we do not need to deal with newlines ourselves.
Golang program that gets lines in file
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))
}
Output
Index = 0, line = Thank you
Index = 1, line = Friend
2
Tip: The file contains the lines "Thank you" and then "Friend." So it is a friendly file at least.