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 ( "os" "fmt" "bufio" )

//first open the file file, err := os.Open(filename) if err != nil { fmt.Printf("error opening file: %v\n",err) os.Exit(1) } // 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) } if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-tutorials_technology-medrectangle-3-0')};