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
+11.4k SSL : The certificate is not trusted because no issuer chain was provided
+5.4k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+27.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+16.5k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+6.3k Golang : Combine slices of complex numbers and operation example
+7.9k Golang : Routes multiplexer routing example with regular expression control
+8.6k Golang : Sort lines of text example
+14.9k Golang : Get all local users and print out their home directory, description and group id
+8k Golang : Metaprogramming example of wrapping a function
+23.6k Golang : Use regular expression to validate domain name
+13.5k Golang : Convert spaces to tabs and back to spaces example
+9.8k Golang : Read file and convert content to string