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.7k Golang : Display a text file line by line with line number example
+2.8k Golang : Handling image beyond OpenCV video capture boundary
+9k Golang : How to extract links from web page ?
+14.4k Golang : Write file with io.WriteString
+3.8k Golang : constant 20013 overflows byte error message
+3.5k Golang : Embedded or data bundling example
+15.2k Golang : Record voice(audio) from microphone to .WAV file
+13.1k How to enable MariaDB/MySQL logs ?
+3.8k Android Studio : Checkbox for user to select options example
+4.9k Golang : How to get ECDSA curve and parameters data?
+6k Golang : Find commonalities in two slices or arrays example
+3.7k How to let Facebook Login button redirect to a particular URL ?