Golang : Read a file line by line
Got another newbie to Golang asking me for help today on how to read a file line by line. The simplest way that I can think of is to use the bufio.NewScanner() and scanner.Scan() functions. Below is a sample code for reading a text file line by line.
Content of file.dat
First
Second
Third
Fourth
Fifth
and the program will read the file
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("./file.dat")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
reader := bufio.NewReader(file)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
and output the following
First
Second
Third
Fourth
Fifth
Reference :
See also : Golang : Scanf function weird error in Windows
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.8k Golang Hello World Example
+10.3k Golang : How to flush a channel before the end of program?
+12.5k Golang : Reverse IP address for reverse DNS lookup example
+4.8k Unix/Linux : Get reboot history or check when was the last reboot date
+4.4k Javascript : How to loop over and parse JSON data?
+16.8k Golang : Display list of time zones with GMT
+44.4k Golang : Encode image to base64 example
+14.2k Golang : Get checkbox or extract multipart form data value example
+4.2k Javascript : Change page title to get viewer attention
+61.4k Golang : Convert HTTP Response body to string
+4.4k Golang : Return multiple values from function