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
+4.6k Golang : Get S3 or CloudFront object or file information
+15.7k Golang : How to tell if a file is compressed either gzip or zip ?
+14.7k Golang : Read a file line by line
+18k Golang : How to run your code only once with sync.Once object
+9.1k Golang : Embed secret text string into binary(executable) file
+7.4k Golang : Generate Datamatrix barcode
+23.1k Golang : Time slice or date sort and reverse sort example
+14.1k Golang : How do I get the local IP (non-loopback) address ?
+6.9k Golang : Tell color name with OpenCV example
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+20.6k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+30.6k Golang : Validate email address with regular expression