Read lines from string or file in Golang.
Run Code on Go Playground
import (
"bufio"
"strings"
)
func StringToLines(s string) (lines []string, err error) {
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
err = scanner.Err()
return
}
import (
"bufio"
"os"
)
func FileToLines(filePath string) (lines []string, err error) {
f, err := os.Open(filePath)
if err != nil {
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
err = scanner.Err()
return
}
Tested on: Ubuntu Linux 15.10, Go 1.6.
References: