DEV Community

Onelinerhub
Onelinerhub

Posted on

4 2

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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs