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()
andos.MkdirTemp()
are available since Go 1.17. For older versions you can useioutil.TempFile()
andioutil.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:
dir
which is a directory where a temporary file should be created. If left empty, the default directory for temporary files (for a given OS) is used.pattern
that is used to generate names of temporary files. The name is created by appending a random string to the end of the pattern. In this way, in the example, we get names such astmpfile-483140887
. You can also use*
to indicate where the random string should be placed. Givingtmpfile-*.txt
you get, for example,tmpfile-483140887.txt
.
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
.