How to Write a File in Golang

To write a file in Golang, you can use the “io.WriteString()” function. The “os.Create()” function creates or truncates a file and the io.Writer interface provides a way to write data to the file. The os.File type implements the io.Writer interface, so you can use it directly to write data to the file.

Example

package main

import (
  "fmt"
  "io"
  "log"
  "os"
)

func main() {
  // Define the file path
  filePath := "my_data_file.txt"

  // Create or truncate the file
  file, err := os.Create(filePath)
  if err != nil {
    log.Fatalf("Error creating file: %v", err)
  }
  defer file.Close()

  // Define the data to be written to the file
  data := "Hello, Golang!\n"

  // Write the data to the file
  n, err := io.WriteString(file, data)
  if err != nil {
    log.Fatalf("Error writing to file: %v", err)
  }

  fmt.Printf("Successfully wrote %d bytes to %s\n", n, filePath)
}

Output

Successfully wrote 15 bytes to my_data_file.txt

In this code, we defined the file path as example.txt and used the “os.Create()” function to create or truncate the file. We then defined the data to be written to the file as string data.

In the next step, we used the “io.WriteString()” function to write the data to the file. Finally, we print a success message indicating the number of bytes written to the file.

Go write to file with File.Write/File.WriteAt

To write to a file, you can use the os.Create() function to create a new file, and then call the Write() or WriteAt() method of the returned *os.File object.

package main

import (
  "log"
  "os"
)

func main() {
  // Create a new file
  file, err := os.Create("test.txt")
  if err != nil {
    log.Fatal(err)
  }
  defer file.Close()

  // Write some text to the file
  byteSlice := []byte("Hello, World!")
  offset := int64(5) // Start writing at position 5
  bytesWritten, err := file.WriteAt(byteSlice, offset)
  if err != nil {
    log.Fatal(err)
  }
  log.Printf("Wrote %d bytes.\n", bytesWritten)
}

Output

2023/07/14 16:34:56 Wrote 13 bytes.

Go write to file with ioutil.WriteFile

In Go, the ioutil.WriteFile() function is a convenient way to write a byte slice directly to a file. It handles opening, writing to, and closing the file, all in one function call.

package main

import (
  "io/ioutil"
  "log"
)

func main() {
  // Define the data to write to the file.
  data := []byte("Hello, World!")

  // Write the data to the file.
  err := ioutil.WriteFile("text.txt", data, 0644)
  if err != nil {
    log.Fatal(err)
  }

  log.Println("File written successfully")
}

Output

2023/07/14 16:36:42 File written successfully

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.