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.9k Golang : Display packages names during compilation
+6.9k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+21.5k SSL : How to check if current certificate is sha1 or sha2
+7.1k Golang : Dealing with postal or zip code example
+5.4k Python : Print unicode escape characters and string
+7.2k Golang : Accessing dataframe-go element by row, column and name example
+11k Golang : Simple image viewer with Go-GTK
+5.4k Golang : Stop goroutine without channel
+17.2k Golang : Check if IP address is version 4 or 6
+17.4k Golang : Clone with pointer and modify value
+5.4k PHP : Fix Call to undefined function curl_init() error
+16.3k Golang : Send email and SMTP configuration example