How to Read a File Line by Line to String in Golang?

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
    }
}

chevron_right


Output:

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.