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
+9.6k Golang : Format strings to SEO friendly URL example
+10k Golang : Identifying Golang HTTP client request
+6.8k Golang : How to setup a disk space used monitoring service with Telegram bot
+20.1k Golang : Check if os.Stdin input data is piped or from terminal
+7.3k Golang : Word limiter example
+15.1k Golang : Get timezone offset from date or timestamp
+33.7k Golang : convert(cast) bytes to string
+3.3k Golang : Fix go-cron set time not working issue
+30.3k Golang : Generate random string
+5.2k Javascript : Shuffle or randomize array example
+15.9k Golang : How to reverse elements order in map ?
+17.8k Golang : Get all upper case or lower case characters from string example