0
0
GoHow-ToBeginner · 3 min read

How to Write a File in Go: Simple Guide with Examples

In Go, you can write a file using the os.WriteFile function by providing the filename, data as a byte slice, and file permissions. Alternatively, you can open a file with os.Create and write data using the Write method.
📐

Syntax

The simplest way to write data to a file is using os.WriteFile. It takes three arguments:

  • filename: the name of the file to write to
  • data: the content as a byte slice ([]byte)
  • perm: file permissions (e.g., 0644)

This function creates the file if it does not exist or overwrites it if it does.

go
err := os.WriteFile("example.txt", []byte("Hello, Go!"), 0644)
if err != nil {
    // handle error
}
💻

Example

This example shows how to write the string "Hello, Go!" to a file named hello.txt using os.WriteFile. It also handles errors properly.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    data := []byte("Hello, Go!\n")
    err := os.WriteFile("hello.txt", data, 0644)
    if err != nil {
        fmt.Println("Error writing file:", err)
        return
    }
    fmt.Println("File written successfully")
}
Output
File written successfully
⚠️

Common Pitfalls

Common mistakes when writing files in Go include:

  • Not handling errors returned by file operations, which can cause silent failures.
  • Using incorrect file permissions, which may prevent reading or writing later.
  • Forgetting to convert strings to byte slices before writing.
  • Using os.Create without closing the file, which can cause resource leaks.

Always check errors and close files when using os.Create or os.OpenFile.

go
/* Wrong way: forgetting to close file and ignoring errors */

f, _ := os.Create("bad.txt")
f.Write([]byte("data"))

/* Right way: handle errors and close file */

f, err := os.Create("good.txt")
if err != nil {
    // handle error
}
defer f.Close()
_, err = f.Write([]byte("data"))
if err != nil {
    // handle error
}
📊

Quick Reference

Summary tips for writing files in Go:

  • Use os.WriteFile for simple file writing in one step.
  • Use os.Create and Write for more control (e.g., appending).
  • Always handle errors returned by file operations.
  • Use file permissions like 0644 to allow owner read/write and others read.
  • Close files after writing to free resources.

Key Takeaways

Use os.WriteFile for quick and simple file writing with filename, data, and permissions.
Always handle errors returned by file operations to avoid silent failures.
Close files after writing when using os.Create or os.OpenFile to prevent resource leaks.
Convert strings to byte slices before writing to files.
Set appropriate file permissions like 0644 for common read/write access.