Go by Example: Temporary Files and Directories

The Go standard library provides the os and ioutil packages for working with temporary files and directories. Here’s an example that demonstrates how to use these packages to work with temporary files and directories:

package main

import (

func main() {
	// Create a temporary directory
	dir, err := ioutil.TempDir("", "temp_dir_")
	if err != nil {
		fmt.Println("Error creating temporary directory:", err)
	defer os.RemoveAll(dir) // Clean up the directory when we're done
	fmt.Println("Temporary directory created:", dir)

	// Create a temporary file in the directory
	file, err := ioutil.TempFile(dir, "temp_file_")
	if err != nil {
		fmt.Println("Error creating temporary file:", err)
	defer os.Remove(file.Name()) // Clean up the file when we're done
	fmt.Println("Temporary file created:", file.Name())

	// Write some data to the file
	_, err = file.Write([]byte("temporary data"))
	if err != nil {
		fmt.Println("Error writing to file:", err)

In this example, we use the ioutil.TempDir function to create a temporary directory, and the ioutil.TempFile function to create a temporary file within that directory. The ioutil.TempDir and ioutil.TempFile functions both take two arguments: the first is the directory in which to create the temporary directory or file, and the second is a prefix for the name of the directory or file.

We use the defer keyword to ensure that the temporary directory and file are cleaned up when we’re done with them, by calling os.RemoveAll and os.Remove, respectively.

Finally, we write some data to the file using the Write method on the file object returned by ioutil.TempFile.


Leave a Reply

Your email address will not be published. Required fields are marked *