Complete Guide to the os Package in Go

The Go os package provides a portable interface to operating system functionality like file I/O, environment variables, and process control.

The os package in Go provides a platform-independent interface to operating system functionality like file handling, environment variables, and process management. Use os.Open to read files, os.Setenv to configure variables, or os.Exit to terminate the program.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Read an environment variable
	name := os.Getenv("USER")
	fmt.Println("Hello,", name)

	// Create a new file
	file, err := os.Create("example.txt")
	if err != nil {
		fmt.Println("Error creating file:", err)
		os.Exit(1)
	}
	defer file.Close()

	// Write to the file
	_, err = file.WriteString("Hello, OS package!")
	if err != nil {
		fmt.Println("Error writing to file:", err)
	}

	fmt.Println("File created successfully.")
}