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
+1.9k Golang : Map within a map example
+1.5k Golang : How to get username from email address
+14.6k Golang : All update packages with go get command
+4.7k Golang : Convert IPv4 address to packed 32-bit binary format
+3.3k Golang : How to check variable or object type during runtime?
+2.1k Unix/Linux : How to pipe/save output of a command to file?
+12.7k How to enable MariaDB/MySQL logs ?
+4.4k Swift : Convert (cast) Character to Integer?
+9.8k Golang : How to get time from unix nano example
+2.7k Golang : Reverse by word
+2.5k Golang : Sort lines of text example
+8.8k Golang : Parsing or breaking down URL