Go, Software Development

Golang – Read Text File Line by Line With The Bufio Package

This post shows how Golang can read a text file line by line using a buffered IO or bufio package. The content of a file may be in Chinese or English because Golang supports UTF-8 by default. Moreover, we do not need third-party libraries for our purpose because Golang comes with the bufio package. This package allows us to read and even write text to files.

The Golang bufio Package

The bufio package is a Golang package that comes with the Go SDK. We need to scan a text file line by line because it has the Scanner type. Suppose we have the following content for a tex file. How do we read each line in Golang using the bufio package? Moreover, it provides convenient ways to perform file read and write.

Golang Codes To Read Text

Consider the following simple Golang codes, which use the bufio package and the fmt and os packages. Before we can even read lines of texts from a file, we need to open an existing text file. Therefore, we need to use the os package to use the Open function.

Then, we use the NewScanner function from the bufio package so the codes can scan the lines from the text file one by one. Next, we use the Scan function, which picks one line at a time from the text file.

Test Golang Codes

We get the following output when we run the codes in our IDEs. Note that our codes are in the HelloWorld.go file only, and the other .go  files on the screenshot below belong to the bufio package.

Meanwhile, we can also use Golang to write the same lines of texts to another text file. As we can see, the Golang codes to read text files are similar to those for writing text files.

Would you please check the Golang documentation for more information?

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like