Writing Files
In this page:
Writing a File in One Call
os.WriteFile creates (or overwrites) a file with the given byte slice as its full contents, in a single convenient call -- the simplest way to save small amounts of data.
Example: Writing a File in One Call
package main
import (
"fmt"
"io/ioutil"
)
func main() {
err := ioutil.WriteFile("output.txt", []byte("Go makes file I/O simple"), 0644)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("file written successfully")
}
Login to try C/C++/Java/PHP code in the editor
Writing Incrementally with os.Create
os.Create opens a file for writing, creating it if it doesn't exist or truncating it if it does, and returns a *os.File you can call Write on multiple times before closing.
Note: Always defer file.Close() to ensure buffered writes are flushed to disk.
Example: Writing Incrementally with os.Create
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Create("log.txt")
if err != nil {
fmt.Println("error:", err)
return
}
defer f.Close()
f.WriteString("first line\n")
f.WriteString("second line\n")
fmt.Println("wrote two lines")
}
Login to try C/C++/Java/PHP code in the editor
Appending to an Existing File
To add data without erasing what's already there, open the file with os.OpenFile using the O_APPEND and O_WRONLY flags, rather than os.Create which always starts the file empty.
Example: Appending to an Existing File
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
ioutil.WriteFile("history.txt", []byte("entry 1\n"), 0644)
f, err := os.OpenFile("history.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("error:", err)
return
}
defer f.Close()
f.WriteString("entry 2\n")
data, _ := ioutil.ReadFile("history.txt")
fmt.Println(string(data))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the permission bits argument to os.WriteFile (like 0644), which controls who can read/write the file.
- Opening a file with os.Create when you actually meant to append to an existing one -- Create always truncates.
- Not closing a file opened for writing before the program exits, risking buffered data never actually reaching disk.
- os.WriteFile writes a full byte slice to a file in one call, creating or truncating it as needed.
- os.Create opens (or truncates) a file for writing, requiring an explicit Close().
- File permission bits, like 0644, control read/write/execute access on Unix-like systems.
- os.OpenFile with the O_APPEND flag is used to add data to the end of an existing file.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: