Skip to content
Related Articles

Related Articles

How to Read a File Line by Line to String in Golang?
  • Last Updated : 22 Jun, 2020

To read a file line by line the bufio package Scanner is used. Let the text file be named as sample.txt and the content inside the file is as follows:

GO Language is a statically compiled programming language, It is an open-source language. It was designed at Google by Rob Pike, Ken Thompson, and Robert Grieserner. It is also known as Golang. Go language is a general-purpose programming language mainly meant for building large scale complex software.




package main
  
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
  
func main() {
  
    // os.Open() opens specific file in 
    // read-only mode and this return 
    // a pointer of type os.
    file, err := os.Open("sample.txt")
  
    if err != nil {
        log.Fatalf("failed to open")
  
    }
  
    // The bufio.NewScanner() function is called in which the
    // object os.File passed as its parameter and this returns a
    // object bufio.Scanner which is further used on the
    // bufio.Scanner.Split() method.
    scanner := bufio.NewScanner(file)
  
    // The bufio.ScanLines is used as an 
    // input to the method bufio.Scanner.Split()
    // and then the scanning forwards to each
    // new line using the bufio.Scanner.Scan()
    // method.
    scanner.Split(bufio.ScanLines)
    var text []string
  
    for scanner.Scan() {
        text = append(text, scanner.Text())
    }
  
    // The method os.File.Close() is called
    // on the os.File object to close the file
    file.Close()
  
    // and then a loop iterates through 
    // and prints each of the slice values.
    for _, each_ln := range text {
        fmt.Println(each_ln)
    }
}

Output:

Read-a-file-line-by-line-to-string-in-Golang




My Personal Notes arrow_drop_up
Recommended Articles
Page :