Skip to main content

Using Go to write to a file, but only if it doesn’t exist yet

  • Tagged with golang
  • Posted

Opening a file with os.O_CREATE|os.O_EXCL will ensure you only create the file if it doesn’t already exist.

In Go, if you want to write to a file, but only if it doesn’t exist (an “exclusive write”), you can call os.OpenFile with a couple of flags:

f, err := os.OpenFile(fname, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666)

Here’s an example program:

package main

import (
	"log"
	"os"
)

func main() {
	fname := "greeting.txt"

	f, err := os.OpenFile(fname, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666)
	if err != nil {
		if os.IsExist(err) {
			log.Fatalf("File already exists: %s\n", fname)
		} else {
			log.Fatalf("Error creating file: %v\n", err)
		}
	}
	defer f.Close()

	_, err = f.WriteString("hello world\n")
	if err != nil {
		log.Fatalf("Error writing to file: %v\n", err)
	}

	log.Printf("Created file successfully: %s\n", fname)
}

Here’s what happens when you run it:

$ go run exclusive_write.go
Created file successfully: greeting.txt

$ go run exclusive_write.go
File already exists: greeting.txt
exit status 1