How to Write File in Golang

In programming, you will come across file handling and the basics of file operations at some point. Of course, reading and writing files are the most basic operations. In this case, to make things easy, all you need to know is how this data is structured so that you can parse and modify it to suit your needs.

Golang has built-in packages like os and io that provide file create, open, read, and write functions to handle file management operations. This is because there are so many ways to write files in Golang.

Golang file write

To write a string in a file in Golang, use the os.WriteString() function. The WriteString() is like a Write() function, but it writes the contents of string s rather than a slice of bytes.

// hello.go

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("test.txt")
	if err != nil {
		fmt.Println(err)
		return
	}
	l, err := f.WriteString("LG 32 INCH Smart TV For My Company")
	if err != nil {
		fmt.Println(err)
		f.Close()
		return
	}
	fmt.Println(l, "bytes written successfully")
	err = f.Close()
	if err != nil {
		fmt.Println(err)
		return
	}
}

First, we have imported two fmt and os packages in the above code.

Inside the main() function, The os.Create() function creates the file named test.txt. If a file with that name already exists, then a create function truncates the file. This function returns the File descriptor.

First, we create a file and then use the WriteString() function to write the bytes into a newly created file. The method returns several bytes written and errors if any.

It writes a string rather than a slice of bytes. So now, if you check in the file directory, there is a new file called test.txt, and if you open that file, you will see “LG 32 INCH Smart TV For My Company“.

In the console, your output looks like this.

go run hello.go
34 bytes written successfully

If the file is not created, then we can create a file using os.Create() function or some functions create a file on the fly and then write the files. Some of the file writing methods are the following.

  1. We can use the os package to write in the file.
  2. Write bytes in the file.
  3. Write the data line by line.
  4. We can use the io/ioutil package to write in the file.
  5. We can write log files.

Writing bytes to a file

To write bytes into the file in Golang, use the os.Write() function.

func (*File) Write

See the following syntax.

func (f *File) Write(b []byte) (n int, err error)

The Write() function writes len(b) bytes to the File. It returns several bytes written and an error if any. The Write() function returns a non-nil error when n != len(b).

See the following example. We will write “AppDividend” to a newly created file.

// hello.go

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("test.txt")
	if err != nil {
		fmt.Println(err)
		return
	}

	d2 := []byte{65, 112, 112, 68, 105, 118, 105, 100, 101, 110, 100}
	n2, err := f.Write(d2)
	if err != nil {
		fmt.Println(err)
		f.Close()
		return
	}
	fmt.Println(n2, "bytes written successfully")
	err = f.Close()
	if err != nil {
		fmt.Println(err)
		return
	}
}

The os.Write() method writes a slice of bytes to a file named test.txt in the same directory as hello.go file. You can change the directory however you want.

After running your program, if you open the test.txt file, you will see “AppDividend” written in the file.

The console output is the following.

➜  go run hello.go
11 bytes written successfully

Writing strings line by line to a file in Go

We can use the range() function to write strings line by line.

Then we use fmt.Fprintln() function to write strings line by line.

See the following code.

// hello.go

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("test.txt")
	if err != nil {
		fmt.Println(err)
		f.Close()
		return
	}
	d := []string{"The Mandalorian", "Game of Thrones", "Stranger Things"}

	for _, v := range d {
		fmt.Fprintln(f, v)
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	err = f.Close()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("file was written line by line successfully")
}

We iterate through the array using a for range loop and use the Fprintln function to write the lines to a file.

Let’s deep dive more into Fprintln() function.

func Fprintln()

The Fprintln function takes an io.writer as a parameter and appends a new line, just what we wanted. Running this program will be written in the file.

See the following syntax.

func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

Golang Fprintln() function uses the default formats for its operands and writes to w.

Spaces are always added between the operands, and a newline is appended. It returns the number of bytes written, and any write error encountered.

Now, back to the program; let’s run the above code and see the output.

go run hello.go
file was written line by line successfully

Now, open the test.txt file, and you will see its content like the following.

The Mandalorian
Game of Thrones
Stranger Things

Use the io/ioutil package to write a file.

We use the io/ioutil package’s WriteFile() method.

The package ioutil implements some I/O utility functions.

func WriteFile()

See the syntax.

func WriteFile(filename string, data []byte, perm os.FileMode) error

It takes three parameters.

  1. filename/filepath
  2. data
  3. file permission

Golang WriteFile() writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm; otherwise, WriteFile truncates it before writing.

Let’s import the io/ioutil package and use the WriteFile() method.

See the following code.

// hello.go

package main

import (
	"io/ioutil"
)

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {
	d2 := []byte{65, 112, 112, 68, 105, 118, 105, 100, 101, 110, 100}
	err := ioutil.WriteFile("test.txt", d2, 0644)
	check(err)
}

Run the file and see the output.

You can open the test.txt file and see its content, which is “AppDividend“.

The ioutil.WriteFile() function will create a file if it does not exist, and if it exists, then truncate it and write the provided data in that file.

func io.WriteString()

Golang WriteString() writes the contents of the string s to w, which accepts a slice of bytes. If w implements StringWriter, its WriteString method is invoked directly. Otherwise, w.Write is called exactly once.

See the following code.

// hello.go

package main

import (
	"io"
	"log"
	"os"
)

func main() {
	err := WriteToFile("test.txt", "The Witcher")
	if err != nil {
		log.Fatal(err)
	}
}

// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func WriteToFile(filename string, data string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.WriteString(file, data)
	if err != nil {
		return err
	}
	return file.Sync()
}

In the above code, we have created a separate function called WriteToFile(), which takes two arguments.

  1. Filename
  2. data

Then we used the WriteString() method to write the data. All the code is self-explanatory.

Run the above code, and the test.txt file will be created and written with “The Witcher“.

Conclusion

File operations like creating, opening, reading, and writing a file in Golang are elementary, and many functions and packages are available to do the job for you.

In this example, we have seen io, os, and fmt packages, and all the packages are related to performing I/O operations in Golang.

We have seen how to write a string in a file, write strings line by line, and write the file using the ioutil package.

I hope this tutorial will solve all your problems and question regarding how to write files in Golang.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.