Standard library / os

os.Create()

Creates or truncates a file for read/write; close the returned file and check write errors. Example uses a disposable temporary workspace. Expected stdout: 'go\n'.

Formal Syntax & Structure

go syntaxgo
func Create(name string) (*File, error)

Parameters & Attributes

NameTypeDescription
namestringName or pathname of the target.

Return Value

(*File, error)

Creates or truncates a file for read/write; close the returned file and check write errors.

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()()  f, e := os.Create("a.txt")  check(e)  _, e = f.WriteString("go")  check(e)  check(f.Close())  b, e := os.ReadFile("a.txt")  check(e)  fmt.Println(string(b))}
Go Reference