[Golang] Read Lines From File or String



Readlines From String

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
}

Readlines From File

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:

[1]golang read lines from file - Google search
[2]
[3]os - The Go Programming Language
[4]fmt - The Go Programming Language
[5]strings - The Go Programming Language
[6][Golang] Read Lines From URL
[7]Processing of huge text files : golang