❮ Files
❯
- Open
- os.Open
- bufio
- NewScanner
- Scan
Read file line-by-line with Scanner
- Removes the newlines
examples/read-file-with-scanner/read_file_with_scanner.go
package main import ( "bufio" "fmt" "os" ) func main() { filename := "random.txt" fh, err := os.Open(filename) if err != nil { fmt.Printf("Could not open file '%v': %v", filename, err) os.Exit(1) } scanner := bufio.NewScanner(fh) for scanner.Scan() { line := scanner.Text() fmt.Printf("Line: %v\n", line) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading:", err) } }
examples/read-file-with-scanner/random.txt
This is just some random text with more than one lines. This is already the 3rd line.