Temporary files and directories
Context
Section titled “Context”Use os.CreateTemp and os.MkdirTemp to create temporary files/directories. They are automatically cleaned up by the OS or manually with defer os.Remove.
Example
Section titled “Example”Create a temporary file, write data, then delete it.
Code example
Section titled “Code example”package main
import ( "fmt" "os")
func main() { f, err := os.CreateTemp("", "example-*.txt") if err != nil { fmt.Println("Error:", err) return } defer os.Remove(f.Name()) defer f.Close()
f.WriteString("temporary data") fmt.Println("Temporary file:", f.Name())}Output (example)
Section titled “Output (example)”Temporary file: /tmp/example-123456789.txt