golang open file and iterate lines

File iteration with go

In this example to iterate lines of a file with go we used bufio.NewScanner First we open the file and then we use the scanner to iterate

import (

//first open the file
file, err := os.Open(filename)
if err != nil {
    fmt.Printf("error opening file: %v\n",err)
// create the scanner using the file
scanner := bufio.NewScanner(file)
// we iterate in the next for
// Scan will search for new lines (\n) and it will return the line.
for scanner.Scan() {
    fmt.Println(scanner.Text()) // we print the line
//check for errors
if err := scanner.Err(); err != nil {
    fmt.Fprintln(os.Stderr, "reading standard input:", err)