Step1: How to Read File in Golang
The Go programming language has bufio
package to read the text by lines or words from a file. We will use bufio
package to read the file. We will create Go file main.go
and import necessary packages.
package main import ( "bufio" "fmt" "log" "os" )
Step2: Read File Line By Line in Golang
Now we will create a text file text.txt and open file using os.Open()
function and it returns pointer of type file. We will read file using bufio.NewScanner()
and then read line by line with fileScanner.Split(bufio.ScanLines)
. Then we will loop through lines to append text into variable and finaly loop through to each lines to print each line data.
func main() { readFile, err := os.Open("test.txt") if err != nil { log.Fatalf("failed to open file: %s", err) } fileScanner := bufio.NewScanner(readFile) fileScanner.Split(bufio.ScanLines) var fileTextLines []string for fileScanner.Scan() { fileTextLines = append(fileTextLines, fileScanner.Text()) } readFile.Close() for _, eachline := range fileTextLines { fmt.Println(eachline) } }
Step3: Complete Code to Read File Line by Line using Go
Here is complete code of go file main.go
to read file data line by line. Just run this file to get desired output.
package main import ( "bufio" "fmt" "log" "os" ) func main() { readFile, err := os.Open("test.txt") if err != nil { log.Fatalf("failed to open file: %s", err) } fileScanner := bufio.NewScanner(readFile) fileScanner.Split(bufio.ScanLines) var fileTextLines []string for fileScanner.Scan() { fileTextLines = append(fileTextLines, fileScanner.Text()) } readFile.Close() for _, eachline := range fileTextLines { fmt.Println(eachline) } }
Step4: Run Read File Line by Line using Go Example
Now finally we will run our main.go
file with above code using go run command to read file line by line and display data.
C:\golang>go run main.go
We will see the read text file data line by line as output on console.
No comments:
Post a Comment