Search⌘ K
AI Features

Writing to a File

Explore four different methods to write data to files in Go, including creating, appending, and using byte slices for efficient output. Understand how these approaches work with Go's io.Writer interface and file handling in UNIX systems.

How to write data to files

So far, we have seen ways to read files. This lesson shows how to write data to files in four different ways and how to append data to an existing file.

Coding example

The code of writeFile.go is as follows:

Go (1.19.0)
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
buffer := []byte("Data to write\n")
f1, err := os.Create("/tmp/f1.txt")

os.Create() returns an *os.File value associated with the file path that is passed as a parameter. Note that if the file already exists, os.Create() truncates it.

Go (1.19.0)
if err != nil {
fmt.Println("Cannot create file", err)
return
}
defer f1.Close()
fmt.Fprintf(f1, string(buffer))
...