You write to a file in Go by opening it with os.Create or os.OpenFile to get a file handle, then using io.WriteString or fmt.Fprintln to write data, and finally calling Close() to ensure data is flushed and resources are released. For robustness, always check for errors at each step and consider using defer to guarantee the file closes even if the program panics.
Here is a simple example using os.Create, which truncates the file if it exists or creates it if it doesn't:
package main
import (
"fmt"
"os"
)
func main() {
// Create or truncate the file
file, err := os.Create("output.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close() // Ensures file is closed when main returns
// Write data to the file
_, err = fmt.Fprintln(file, "Hello, Go!")
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
fmt.Println("File written successfully.")
}
If you need more control over file permissions or want to append to an existing file instead of overwriting it, use os.OpenFile with specific flags:
package main
import (
"fmt"
"os"
)
func main() {
// Open file with append mode (O_APPEND) and create if not exists (O_CREATE)
// Permissions are set to 0644 (rw-r--r--)
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Write a line
_, err = file.WriteString("New log entry\n")
if err != nil {
fmt.Println("Error writing:", err)
return
}
}
Key takeaways for production code: always handle the error returned by Create or OpenFile immediately. Use defer file.Close() right after successfully opening the file to prevent resource leaks. If you are writing large amounts of data, consider using bufio.NewWriter for buffered I/O performance, but remember to call Flush() before closing.