Standard library / os

os.WriteFile()

Creates or truncates a named file and writes data; errors can leave partial content. Existing file permissions are not replaced. Example uses a disposable temporary workspace. Expected stdout: 'go\n'.

Formal Syntax & Structure

go syntaxgo
func WriteFile(name string, data []byte, perm FileMode) error

Parameters & Attributes

NameTypeDescription
namestringName or pathname of the target.
data[]byteBytes to write.
permFileModeRequested permissions before umask when creating.

Return Value

error

Creates or truncates a named file and writes data; errors can leave partial content.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os")
func check(e error) {  if e != nil {    panic(e)  }}func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  check(os.WriteFile("a.txt", []byte("go"), 0600))  b, e := os.ReadFile("a.txt")  check(e)  fmt.Println(string(b))}
Go Reference