0Pricing
Go Academy · Lesson

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

  1. Reading Files with os and bufio
  2. Writing Files and Temp Files
  3. JSON Encoding and Decoding
  4. Streaming JSON and CSV
← Back to Go Academy