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.
1 2 | 我想吃! I want to eat! |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import ( "bufio" "fmt" "os" ) func main() { // Open the file. f, _ := os.Open("C:\\Users\\abc\\data.txt") // Create a Scanner for the file scanner := bufio.NewScanner(f) // Read and print each line in the file for scanner.Scan() { line := scanner.Text() fmt.Println(line) } } |
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?