← Back to Gists

Read file lines

📝 Go
mklein
mklein · Level 7 ·

Reads all lines from a file into a slice of strings using Go's bufio scanner.

Go
package main import ( "bufio" "os"
) func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err()
}

Comments

1
tommy_washington tommy_washington

@mmontoya bufio.Scanner handles large files gracefully, but for small files you might prefer os.ReadFile and strings.Split for simplicity.