Write files in GoLang

In this post, we are going to explore how to write into files in GoLang. Go has the ioutil package which makes writing a file a lot easier. So, let’s see what are the ways we can do it.

First step: Creating a File

In order to write something inside a file, we must create the file for writing. Here are the steps necessary to create a file.

f, err := os.Create("filename.ext")       // creates a file at current directory
if err != nil {
        fmt.Println(err)
}

Also, we don’t want to forget closing that file. So, immediately using defer to close the file is an idiomatic way in Go.

defer f.Close()

Write strings in a file

Here are some of the ways to write strings in a file.

1. Using the ioutil package

The ioutil package has a function called WriteFile, which can be used to directly write some strings in a file without much effort. It will be converted to a byte slice and then write it inside the file. Here is an example showing that. In this function, we need to insert the file mode as well. We will put 0644 for it.

package main

import (
    "io/ioutil"
)

func main() {
    s := []byte("This is a string")                // convert string to byte slice
    ioutil.WriteFile("testfile.txt", s, 0644)      // the 0644 is octal representation of the filemode
}
Write To A File Ioutil
Write To A File ioutil

2. Using a more conventional approach

The style to follow here is as follows:

  1. Create a file for writing.
  2. Close it immediately using defer so that it gets closed after all the operations are done on it.
  3. Write inside it

Here is an example showing how it’s done.

package main

import (
    "fmt"
    "os"
    //"io/ioutil"
)

func main() {
  
  // create the file 
  f, err := os.Create("test.txt")
  if err != nil {
    fmt.Println(err)
  }
  // close the file with defer
  defer f.Close()

  // do operations

  //write directly into file
  f.Write([]byte("a string"))

  // write a string
  f.WriteString("\nThis is a pretty long string")

  // // write from a specific offset
  f.WriteAt([]byte("another string"), 42)     // 12 is the offset from start
}
Write To A File
Write To A File

In the code above, the write function writes into the file directly.

The WriteString function does exactly what is says, writes a string into a file.

The WriteAt function takes two arguments, the string converted into bytes array and an offset. The function writes the string at that offset in that file.

3. Append to an existing file

Appending to an existing file is simple. We open the file and then append using the Fprintln function.

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
    newLine := "This is a string which will be appended."
    _, err = fmt.Fprintln(f, newLine)
    if err != nil {
      fmt.Println(err)
    }
}
Append String To File
Append String To File

These are some of the ways file writing operations are handled in Go.