How to Create, Open, and Delete Files in Go

Use os.Create, os.Open, and os.Remove from the standard library to handle file creation, reading, and deletion in Go.

Use the os package to create, open, and delete files with os.Create, os.Open, and os.Remove. Always check for errors returned by these functions to handle failures gracefully.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Create a new file (or truncate if exists)
	file, err := os.Create("example.txt")
	if err != nil {
		fmt.Println("Error creating file:", err)
		return
	}
	defer file.Close()

	// Open an existing file for reading
	readFile, err := os.Open("example.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer readFile.Close()

	// Delete the file
	err = os.Remove("example.txt")
	if err != nil {
		fmt.Println("Error deleting file:", err)
	}
}