Go - Files & I/O

Beginner 10/10 Teacher 10/10 Architect 10/10
Try it: Create a file note.txt and print its contents with os.ReadFile.

Read File

b, err := os.ReadFile("input.txt")
if err != nil { /* handle */ }
fmt.Println(string(b))

Write File

err := os.WriteFile("out.txt", []byte("hello"), 0644)

Streaming

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

Common errors

  • Ignoring errors from file operations—always check and handle err.
  • Forgetting to close files when using os.Open.

Practice

  • Append a line to a file safely and print the updated content.

Quick quiz

  1. When do you need to call Close() on a file?
Show answer When you open a file handle (e.g., with os.Open); not required with os.ReadFile/os.WriteFile.