Reading Files with os and bufio
Open, read lines, and close files safely
os.ReadFile
os.ReadFile (Go 1.16+) reads an entire file into a byte slice in one call. Simple and idiomatic for small files.
data, err := os.ReadFile("config.json")
if err != nil { log.Fatal(err) }
fmt.Println(string(data))os.Open and manual close
For more control, open a file with os.Open (read-only) and close it with defer:
f, err := os.Open("data.txt")
if err != nil { return err }
defer f.Close()All lessons in this course
- Reading Files with os and bufio
- Writing Files and Temp Files
- JSON Encoding and Decoding
- Streaming JSON and CSV