Go, Software Development

Golang – Write Text to File Line by Line Using Buffered IO

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?

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.

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.

Then, we open the file2.txt to see the content as shown below.

For more information, please see Golang’s documentation.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like