RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 14: Reading and Writing Files in Go – Like Using a Diary 📖✍️

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

Files are everywhere: logs, configs, saved game data, even text you type.
In Go, working with files is super simple.
Let’s start with the basics.

We need the os and io/ioutil or os and bufio packages for file stuff.

import (
  "fmt"
  "os"
  "io/ioutil"
)

Let’s write "Hello, Go!" into a file.

func main() {
  err := ioutil.WriteFile("myfile.txt", []byte("Hello, Go!"), 0644)
  if err != nil {
    fmt.Println("Error writing:", err)
  }
}

💡 What’s 0644? That’s the file permission (like read/write). Just copy it for now.

Let’s read the file we just wrote:

func main() {
  data, err := ioutil.ReadFile("myfile.txt")
  if err != nil {
    fmt.Println("Error reading:", err)
    return
  }
  fmt.Println(string(data))
}

It prints:

Hello, Go!

What if you want to add more lines to the same file?

func main() {
  f, err := os.OpenFile("myfile.txt", os.O_APPEND|os.O_WRONLY, 0644)
  if err != nil {
    fmt.Println("Error opening:", err)
    return
  }
  defer f.Close()
  if _, err := f.WriteString("\nMore content here!"); err != nil {
    fmt.Println("Error writing:", err)
  }
}

Want to remove a file?

os.Remove("myfile.txt")

Poof! Gone.

  • Save logs

  • Load configuration

  • Store user preferences

  • Write and read data like CSV, JSON, etc.

  • Use ioutil.WriteFile() to create/write files

  • Use ioutil.ReadFile() to read

  • Use os.OpenFile() with O_APPEND to add more content

  • Always check for errors

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.