Open, close and create files locally
Open, close and create files locally
An os.File represents an open operating-system file. Open reads an existing file; Create creates or truncates a file for reading and writing. Both can fail. Run these examples in their own temporary directory: lab creates it, cleanup removes only that directory, and check aborts on an unexpected error. In applications return errors to the caller instead of panicking.
package main
import ( "fmt" "io" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() p := filepath.Join(d, "note.txt") f, e := os.Create(p) check(e) _, e = f.WriteString("hello") check(e) check(f.Close()) r, e := os.Open(p) check(e) defer func() { check(r.Close()) }() b, e := io.ReadAll(r) check(e) fmt.Println(string(b))}Close the writer and check the result before reopening. ReadAll is appropriate here only because the input is tiny and controlled. A deferred close after a successful open releases a read handle even on an early return. Close is not a durability guarantee.
Expected output:
helloCreate without overwriting
package main
import ( "errors" "fmt" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() p := filepath.Join(d, "note.txt") f, e := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) check(e) check(f.Close()) _, e = os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) fmt.Println(errors.Is(e, os.ErrExist))}OpenFile accepts flags combined with |. O_EXCL with O_CREATE rejects an existing name rather than truncating it. 0600 is an octal permission request; the OS can restrict or interpret it differently. Never use Create on valuable data without an explicit overwrite policy.
Expected output:
trueTry it locally
In a temporary directory write "go" with os.Create, close it, then read it using os.ReadFile and print it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 01: Open, close and create files locally
Check the lesson objective before moving on.
What does Create do to an existing regular file?
Which flags prevent overwriting an existing name when creating?