⌛ Temporary file in Go - how to create?

introduction file

When you write a program that processes large amounts of data, or you test a program that creates files, you often need the ability to create temporary files that allow you to store your data for a short time without cluttering your project’s disk space. In Go, you can create a temporary file with os.CreateTemp() function and a temporary directory with os.MkdirTemp() function.

os.CreateTemp() and os.MkdirTemp() are available since Go 1.17. For older versions you can use ioutil.TempFile() and ioutil.TempDir().

Create a temporary file

package main

import (
    "log"
    "os"
)

func main() {
    // create and open a temporary file
    f, err := os.CreateTemp("", "tmpfile-") // in Go version older than 1.17 you can use ioutil.TempFile
    if err != nil {
        log.Fatal(err)
    }

    // close and remove the temporary file at the end of the program
    defer f.Close()
    defer os.Remove(f.Name())

    // write data to the temporary file
    data := []byte("abc abc abc")
    if _, err := f.Write(data); err != nil {
        log.Fatal(err)
    }
}

The function func CreateTemp(dir, pattern string) (*File, error) has two parameters:

If you don’t use the temporary file anymore, it is a good practice to remove it using os.Remove().

Create a temporary directory

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    // create a temporary directory
    name, err := os.MkdirTemp("", "dir") // in Go version older than 1.17 you can use ioutil.TempDir
    if err != nil {
        log.Fatal(err)
    }

    // remove the temporary directory at the end of the program
    defer os.RemoveAll(name)

    // print path of the directory
    fmt.Println(name)
}

Parameters of the func MkdirTemp(dir, pattern string) (string, error) function work the same way as in the case of os.CreateTemp(). As before, after you finish working with the temporary folder, you should remember to delete it, for example, via os.RemoveAll.

📁 Create a directory in Go

Learn how to create a single or a hierarchy of directories
introduction file

📎 Convert JSON to CSV in Go

Learn how to transform JSON file to CSV
introduction file json csv

🔄 Convert CSV to JSON in Go

Learn how to transform CSV file data to JSON
introduction file csv json