Go, Software Development

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

Golang Write Text File

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. It has the Scanner type that we need to scan a text file line by line. Suppose we have the following content for a tex file. How do we go about reading 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

When we run the codes in our IDEs, we get the following output. 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? Please visit our Facebook page!

You Might Also Like