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
+14.1k Golang : concatenate(combine) strings
+46.7k Golang : Marshal and unmarshal json.RawMessage struct example
+8.4k Golang : Convert word to its plural form example
+12.4k Golang : How to display image file or expose CSS, JS files from localhost?
+5.7k Python : Print unicode escape characters and string
+5.8k Linux/Unix/PHP : Restart PHP-FPM
+11k Golang : Create Temporary File
+8.2k Golang : Append and add item in slice
+11.6k SSL : The certificate is not trusted because no issuer chain was provided
+5.3k Golang : The Tao of importing package
+10.8k Golang : Underscore string example
+14.7k Golang : GUI with Qt and OpenCV to capture image from camera