File I/O Tutorial - Read, Write, Scanner & Append | Go Tutorial #22
Video: File I/O Tutorial - Read, Write, Scanner & Append | Go Tutorial #22 by Taught by Celeste AI - AI Coding Coach
Take the quiz on the full lesson page
Test what you've read · interactive walkthrough
File I/O in Go: Reading, Writing, Scanning & Appending
Working with files is essential for many Go applications, and this tutorial demonstrates how to read, write, scan, and append to files efficiently. You'll learn to open files, read their contents fully or line-by-line, write new data, and append to existing files using Go's standard libraries.
Code
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
// Reading a file fully
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
content, err := io.ReadAll(file)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println("Full file content:")
fmt.Println(string(content))
// Getting file info
info, err := os.Stat("example.txt")
if err == nil {
fmt.Printf("File size: %d bytes\n", info.Size())
}
// Writing to a new file
newFile, err := os.Create("output.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer newFile.Close()
_, err = newFile.WriteString("Hello, Go file writing!\n")
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
// Reading file line-by-line with Scanner
file.Seek(0, io.SeekStart) // Reset file pointer to start
scanner := bufio.NewScanner(file)
fmt.Println("Reading file line-by-line:")
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("Scanner error:", err)
}
// Appending to a file
appendFile, err := os.OpenFile("output.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening file for appending:", err)
return
}
defer appendFile.Close()
_, err = appendFile.WriteString("Appended line.\n")
if err != nil {
fmt.Println("Error appending to file:", err)
}
}
Key Points
- Use os.Open to open files for reading and defer Close to release resources.
- io.ReadAll reads the entire file content into memory for easy processing.
- bufio.Scanner enables efficient line-by-line reading without loading the whole file.
- os.Create creates or truncates files for writing, while os.OpenFile with flags allows appending.
- Always handle errors and use defer to ensure files are properly closed after operations.
Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.