Writing text to a file is a familiar use case that we may need to implement for our applications. Like most programming languages, Golang has facilities to enable us to implement such write text to files. This post briefly shows how to write texts to a file line by line in Go using buffered IO or bufio.
Write Text To Files With bufio
Sometimes learning a new programming language comes from a need to implement something in that platform. Therefore, the learning could take an agile top-down approach on a specific topic. We know what we want to achieve and only learn specific things to reach that target.
We could use the Golang package bufio to write text to files line-by-line. This package comes with the Go SDK; thus, there is no need to install third-party libraries.
Suppose we have the following texts and we want to write them to a file. How do we do that using Golang and its bufio package?
1 2 | 我想吃! I want to eat! |
Golang Codes To Write Text Files
Consider the following Golang codes. There are four Golang packages in the import statement – bufio, fmt, os, and strconv. Let us go through each package and why we need it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import ( "bufio" "fmt" "os" "strconv" ) func main() { lines := [2]string{"我想吃!", "I want to eat!"} // Create a file for writing f, _ := os.Create("C:\\Users\\abc\\Desktop\\file2.txt") // Create a writer w := bufio.NewWriter(f) for i, s := range lines { fmt.Println(i) w.WriteString(strconv.Itoa(i) + " " + s + "\n") } // Very important to invoke after writing a large number of lines w.Flush() } |
First, the fmt package allows us to output anything on the console, perhaps for feedback to users. Second, the os package enables us to create a file on the file system. Third, the bufio package has functions that actually write text to an existing file. Optionally, we use the strconv to convert numeric values to strings which we use to write to a file.
Test
Before running the codes on your machine, please make sure to change the path ( C:\\Users\\abc\\Desktop\\) to something that exists in your system, e.g., C:\\Users\\<YOUR-USER-NAME>\\Desktop\\.
When we run the codes, we get the following output on the console. Your output may slightly differ from ours.
1 2 3 4 5 6 7 8 | GOROOT=C:\Users\karldev\Desktop\dev\apps\go\sdk\go1.14.4 #gosetup GOPATH=C:\Users\karldev\go #gosetup C:\Users\karldev\Desktop\dev\apps\go\sdk\go1.14.4\bin\go.exe build -o C:\Users\karldev\AppData\Local\Temp\___go_build_MyGo_go.exe C:\Users\karldev\go\src\awesomeProject\MyGo.go #gosetup C:\Users\karldev\AppData\Local\Temp\___go_build_MyGo_go.exe #gosetup 0 1 Process finished with the exit code 0 |
Then, we open the file2.txt to see the content as shown below.
1 2 | 0 我想吃! 1 I want to eat! |
For more information, please see Golang’s documentation.