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
+10.2k Golang : Random Rune generator
+13.5k Golang : Qt progress dialog example
+5.3k Golang : Reclaim memory occupied by make() example
+9.1k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+4.7k JavaScript: Add marker function on Google Map
+5.4k Golang : If else example and common mistake
+17.1k Golang : Find file size(disk usage) with filepath.Walk
+7.7k Golang : Scan files for certain pattern and rename part of the files
+10.8k Golang : Natural string sorting example
+14.2k Golang : Simple word wrap or line breaking example
+13.3k Golang : Linear algebra and matrix calculation example
+27.1k Golang : Find files by name - cross platform example