Go · Stage 8 – Errors and Files · Lesson 48 of 64

Reading a File

Read a small file and handle failure.

Go code

data, err := os.ReadFile("note.txt")
if err != nil {
    fmt.Println("Could not read file")
    return
}
fmt.Println(string(data))
Line-by-line explanation
  1. ReadFile requests all bytes from note.txt.
  2. Err is checked immediately.
  3. String converts bytes to text.
  4. The content is displayed.
Expected output
Hello from the file

This assumes note.txt contains that sentence.