Premium Tutorials • Books • Articles • Modern Programming Paths Go Programming Book · Author Bookstore
Lesson 13 of 15

Working with Files

Read and write text files using Go.

Beginner Friendly Runnable Example Go Programming
Learning objective: Write text to a file and read it back into the program.

Writing Files

Go can create and write files using functions from the os package.

Reading Files

The os.ReadFile function reads the contents of a file into memory.

Handling File Errors

File operations can fail because of missing files, permissions, or invalid paths. Always check errors.

Example Code

Create or update your Go file, then run the program using go run main.go.

package main

import (
    "fmt"
    "os"
)

func main() {
    data := []byte("Learning Go is practical and fun!")

    err := os.WriteFile("message.txt", data, 0644)
    if err != nil {
        fmt.Println("Write error:", err)
        return
    }

    content, err := os.ReadFile("message.txt")
    if err != nil {
        fmt.Println("Read error:", err)
        return
    }

    fmt.Println(string(content))
}
Key points to remember
  • Use []byte when writing text with os.WriteFile.
  • The 0644 value is a common file permission for readable text files.
  • Convert file content to string before printing it as text.

Practice Exercises

  1. Write your name into a text file.
  2. Read the file and print its content.
  3. Handle file errors properly.

Continue Learning

After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.