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.5k Golang : Check if password length meet the requirement
+19.9k Swift : Convert (cast) Int to int32 or Uint32
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+19.5k Golang : Measure http.Get() execution time
+13.1k Android Studio : Password input and reveal password example
+19.4k Golang : Set or Add HTTP Request Headers
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+5.9k Golang : Dealing with backquote
+4.9k Python : Create Whois client or function example
+14.3k Golang : Convert(cast) int to float example
+4.8k Golang : Constant and variable names in native language
+13.8k Golang : Fix image: unknown format error