Essential Go Strings  Edit on GitHub      File Issue

Read file line by line

Often we need to read a file line by line.

Read file into memory and split into lines

// ReadFileAsLines reads a file and splits it into lines
func ReadFileAsLines(path string) ([]string, error) {
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	s := string(d)
	lines := strings.Split(s, "\n")
	return lines, nil
There are 32 lines in 'read_file_as_lines.go'

Iterate over lines in a file

It’s more efficient to only process one line at a time, as opposed to reading the whole file into memory.

We can do that using bufio.Scanner:

func IterLinesInFile(filePath string) error {
    file, err := os.Open(filePath)
    if err != nil {
        return err
    defer file.Close()
    scanner := bufio.NewScanner(file)
    // Scan() reads next line and returns false when reached end or error
    for scanner.Scan() {
        line := scanner.Text()
        // process the line
    // check if Scan() finished because of error or because it reached end of file
    return scanner.Err()
  ↑ ↓ to navigate     ↵ to select     Esc to close