Zest.

Go: Read a file

A short, tested Go example for read a file. Copy it and adjust the names and paths for your project.

Go
data, err := os.ReadFile("data.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))

f, _ := os.Open("data.txt")
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

Find it in Zest

Search for “go read a file” in Zest and this example appears above the results, with other matches to choose from. Searches stay private.

More Go examples

All Go examples