How to process a file line by line in Go?

In the Go programming language, How to process a file line by line?

An equivalent piece of Bash code could be

while read line ; do
    echo $line
done < ./input.txt
asked Aug 3, 2016 by anonymous

1 Answer

You can make use of the bufio package's Scan().

// open the file filepath
f := os.Open(filepath)
// create a scanner
fs := bufio.NewScanner(f)

// scan file https://golang.org/pkg/bufio/#Scanner.Scan
for fs.Scan() {
        txt := fs.Text()
        // do anything with txt
}
answered Oct 10, 2016 by Eric Z Ma (44,280 points)

If you are reading line by line from STDIN:

fs := bufio.NewScanner(os.Stdin)
for fs.Scan() {
    txt := fs.Text()
    // process txt
}
commented Oct 11, 2016 by Eric Z Ma (44,280 points)
How to process a file line by line in Python? asked Mar 17, 2017 by anonymous

Please log in or register to answer this question.

Related questions

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...