Skip to content

Reading files

Go provides several ways to read files: os.ReadFile (entire file), bufio (line by line), os.Open + io.ReadAll, etc. Choose based on file size and needs.

Read an entire file and print its content.

package main
import (
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(data))
}

Output (if example.txt contains “Hello, file!”)

Section titled “Output (if example.txt contains “Hello, file!”)”
Terminal window
Hello, file!