0Pricing
Go Academy · Lesson

os and filepath Packages

Environment variables, paths, and OS interaction

os and filepath Packages is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

os.Args — Command-Line Arguments

os.Args holds the command-line arguments. os.Args[0] is the program name:

package main
import ("fmt"; "os")

func main() {
    fmt.Println("Program:", os.Args[0])
    if len(os.Args) < 2 {
        fmt.Println("Usage: program <name>")
        os.Exit(1)
    }
    fmt.Printf("Hello, %s!\n", os.Args[1])
}

os.Getenv and os.Setenv

Read and write environment variables:

package main
import ("fmt"; "os")

func main() {
    // Read env var (returns "" if not set)
    home := os.Getenv("HOME")
    fmt.Println("HOME:", home)

    // Set env var
    os.Setenv("APP_ENV", "production")
    fmt.Println(os.Getenv("APP_ENV")) // production

    // Get with default pattern:
    port := os.Getenv("PORT")
    if port == "" { port = "8080" }
    fmt.Println("Port:", port)
}

os.Exit — Terminating the Program

os.Exit terminates the program with a status code. Exit 0 = success; non-zero = error. Deferred functions do NOT run:

package main
import ("fmt"; "os")

func main() {
    config := os.Getenv("CONFIG_PATH")
    if config == "" {
        fmt.Fprintln(os.Stderr, "error: CONFIG_PATH not set")
        os.Exit(1)  // signals error to the shell
    }
    fmt.Println("config:", config)
}

os.Open, os.Create, os.ReadFile

File operations with the os package:

package main
import ("fmt"; "os")

func main() {
    // Read entire file
    data, err := os.ReadFile("/etc/hostname")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("hostname: %s", data)

    // Write file (overwrites if exists)
    err = os.WriteFile("/tmp/test.txt", []byte("hello\n"), 0644)
    fmt.Println("write err:", err)
}

os.Stat — File Info

os.Stat returns information about a file or directory:

package main
import ("fmt"; "os")

func main() {
    info, err := os.Stat("/tmp")
    if err != nil {
        if os.IsNotExist(err) {
            fmt.Println("does not exist")
        }
        return
    }
    fmt.Println(info.Name())     // tmp
    fmt.Println(info.IsDir())    // true
    fmt.Println(info.Size())     // size in bytes
    fmt.Println(info.Mode())     // file permissions
    fmt.Println(info.ModTime())  // last modified time
}

os.MkdirAll and os.RemoveAll

Create and remove directory trees:

package main
import ("fmt"; "os")

func main() {
    // Create nested directories
    err := os.MkdirAll("/tmp/myapp/data/logs", 0755)
    fmt.Println("mkdir:", err)

    // Remove a file
    err = os.Remove("/tmp/test.txt")
    fmt.Println("remove:", err)

    // Remove directory and all contents
    err = os.RemoveAll("/tmp/myapp")
    fmt.Println("removeAll:", err)
}

path/filepath: Cross-Platform Paths

path/filepath handles file paths using the OS path separator (/ on Unix, \ on Windows):

package main
import ("fmt"; "path/filepath")

func main() {
    // Join path components correctly
    p := filepath.Join("/home", "user", "docs", "file.txt")
    fmt.Println(p)  // /home/user/docs/file.txt

    // Split path and file
    dir, file := filepath.Split(p)
    fmt.Println(dir, file) // /home/user/docs/ file.txt

    // Extension
    fmt.Println(filepath.Ext(p))  // .txt

    // Base name
    fmt.Println(filepath.Base(p)) // file.txt
}

filepath.Walk — Traversing Directories

Walk a directory tree visiting every file and directory:

package main
import ("fmt"; "os"; "path/filepath")

func main() {
    err := filepath.Walk("/tmp", func(path string, info os.FileInfo, err error) error {
        if err != nil { return err }
        if info.IsDir() {
            fmt.Println("[DIR]", path)
        } else {
            fmt.Printf("[FILE] %s (%d bytes)\n", path, info.Size())
        }
        return nil
    })
    if err != nil { fmt.Println("walk error:", err) }
}

filepath.Glob — Pattern Matching

Find files matching a glob pattern:

package main
import ("fmt"; "path/filepath")

func main() {
    // Find all .go files in current directory
    matches, err := filepath.Glob("*.go")
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, m := range matches {
        fmt.Println(m)
    }

    // Absolute path resolution
    abs, _ := filepath.Abs("../myfile.txt")
    fmt.Println(abs)
}

os.TempDir and os.CreateTemp

Create temporary files safely:

package main
import ("fmt"; "os")

func main() {
    // System temp directory
    fmt.Println(os.TempDir()) // /tmp

    // Create a unique temp file
    f, err := os.CreateTemp("", "myapp-*.json")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer os.Remove(f.Name()) // clean up
    defer f.Close()
    fmt.Println("temp file:", f.Name())
    _, _ = f.WriteString(`{"status":"ok"}`)
}

Quick Check

Which function correctly joins file path components in a cross-platform way?

Recap: os and filepath

Summary:

  • os.Args — command arguments; os.Getenv/Setenv — environment
  • os.ReadFile/WriteFile for simple file I/O
  • os.Stat — file info; os.IsNotExist(err) for missing files
  • os.MkdirAll/RemoveAll for directory management
  • filepath.Join/Split/Ext/Base for cross-platform paths
  • filepath.Walk to traverse directory trees

Frequently asked questions

Is the “os and filepath Packages” lesson free?

Yes — the full text of “os and filepath Packages” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “os and filepath Packages”?

Environment variables, paths, and OS interaction You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “os and filepath Packages” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. fmt and strings Packages
  2. strconv, math and sort
  3. time Package Essentials
  4. os and filepath Packages
← Back to Go Academy