4 cases of reading and writing files in Go

nonunicorn

Onelinerhub

Posted on July 7, 2022

4 cases of reading and writing files in Go

1. How to create empty file in Go

package main
import "os"

func main() {
  file, _ := os.Create("/tmp/go.txt")
  defer file.Close()
}
Enter fullscreen mode Exit fullscreen mode

2. How to create new or overwrite existing file with new content in Go

package main
import "os"

func main() {
  f, _ := os.OpenFile("/tmp/go.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
  defer f.Close()
  f.WriteString("new content\n")
}
Enter fullscreen mode Exit fullscreen mode
  • /tmp/go.txt path to file to create/overwrite
  • os.O_RDWR|os.O_CREATE|os.O_TRUNC means we will either create new or truncate existing file before writing content
  • new content\n new content to write to file

3. How to append line to existing file in Go

package main
import "os"

func main() {
  f, _ := os.OpenFile("/tmp/go.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  defer f.Close()
  f.WriteString("new line\n")
}
Enter fullscreen mode Exit fullscreen mode

Here, we're appending "new line\n" text (with new line symbol at the end) to /tmp/go.txt file. In order to make that right, we need to set os.O_APPEND|os.O_CREATE|os.O_WRONLY permissions.

4. How to read file contents to a string variable:

package main
import "os"

func main() {
  t, _ := os.ReadFile("/tmp/go.txt")
  str := string(t)
}
Enter fullscreen mode Exit fullscreen mode

Here we read everything from /tmp/go.txt file to str variable. Note we're converting read bytes to string using string() function.

More useful Go solutions to work with files

💖 💪 🙅 🚩
nonunicorn
Onelinerhub

Posted on July 7, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related