Golang Write to File
Write File (os.WriteFile Example)
Use os.WriteFile when you want a quick and simple way to write data to a file. It creates the file if it does not exist or overwrites it if it already exists.
package main
import (
"log"
"os"
)
func main() {
data := []byte("Hello, Golang!")
err := os.WriteFile("file.txt", data, 0644)
if err != nil {
log.Fatal(err)
}
}Append to File (os.OpenFile Example)
Use os.OpenFile with the append flag when you want to add data to an existing file without overwriting it.
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("file.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.WriteString("Appending new line\n")
if err != nil {
log.Fatal(err)
}
}Create File in Golang
Using os.Create()
Use os.Create when you want to create a new file or truncate an existing file.
package main
import (
"log"
"os"
)
func main() {
file, err := os.Create("file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
}Key Points
- Creates a new file
- Truncates file if it already exists
- Returns file pointer for further operations
Create File if Not Exists
Use os.OpenFile with os.O_CREATE to create a file only if it does not already exist.
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
}Write to File in Golang
Write Bytes using File.Write()
Use File.Write() when you need low-level control and want to write raw byte data into a file.
package main
import (
"fmt"
"log"
"os"
)
func main() {
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
data := []byte("Hello from Golang\n")
n, err := file.Write(data)
if err != nil {
log.Fatal(err)
}
fmt.Println("Bytes written:", n)
}This approach is commonly used when working with binary data or when precise control over written bytes is required.
Write String using File.WriteString()
Use File.WriteString() when writing plain text strings to a file in Go. It is simpler than converting strings to byte slices.
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.WriteString("Writing string to file in Golang\n")
if err != nil {
log.Fatal(err)
}
}This method is widely used for writing logs, messages, or formatted output to files.
Write File using os.WriteFile (Recommended)
Use os.WriteFile() when you want a simple and direct way to write content to a file in Golang.
package main
import (
"log"
"os"
)
func main() {
err := os.WriteFile("file.txt", []byte("Quick write using os.WriteFile\n"), 0644)
if err != nil {
log.Fatal(err)
}
}This method is recommended for most use cases because it handles opening and closing the file internally. It is ideal when you want to quickly write content to a file without managing file descriptors.
Append to File in Golang
Append using os.OpenFile (O_APPEND)
To append data to a file, use os.OpenFile() with the os.O_APPEND flag.
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("file.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.WriteString("Appending data in Golang\n")
if err != nil {
log.Fatal(err)
}
}This approach ensures that new content is always added to the end of the file without affecting existing data.
Append Multiple Lines Example
You can append multiple lines in a loop when writing logs or continuous data.
package main
import (
"fmt"
"log"
"os"
)
func main() {
file, err := os.OpenFile("file.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
for i := 1; i <= 3; i++ {
_, err := file.WriteString(fmt.Sprintf("Log line %d\n", i))
if err != nil {
log.Fatal(err)
}
}
}This pattern is useful when writing logs, tracking events, or storing repeated output in a file.
Open File for Writing (Flags Explained)
When working with files in Golang, os.OpenFile() gives you full control using flags. These flags define how the file should be opened, whether for writing, appending, or creating if it does not exist.
os.O_CREATE, os.O_WRONLY, os.O_APPEND Explained
These are the most commonly used flags when writing or appending to files in Go.
os.O_CREATEcreates the file if it does not existos.O_WRONLYopens the file in write-only modeos.O_APPENDensures data is added at the end of the file
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY, 0644)In this example, the file will be created if it does not exist and opened for writing.
Common Flag Combinations
In real-world scenarios, multiple flags are combined to achieve the desired behavior.
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)This combination is commonly used for logging systems where:
- the file should be created if missing
- data should always be appended
- existing content should not be overwritten
Another example for overwriting:
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)This will truncate (clear) the file before writing new data.
Read File in Golang (Quick Overview)
Read File using os.ReadFile
Use os.ReadFile() to quickly read the entire content of a file into memory.
package main
import (
"fmt"
"log"
"os"
)
func main() {
data, err := os.ReadFile("file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
}This method is best suited for small to medium-sized files where loading the entire content into memory is acceptable.
When to Use ReadFile vs Scanner
Choosing the right method depends on the size of the file and how you want to process the data.
- Use
os.ReadFilewhen the file is small and you need the entire content at once - Use
bufio.Scannerwhen reading line by line for large files - Use
bufio.Readerwhen you need more control over streaming data
This distinction is important when working with logs, large datasets, or continuous file streams.
Real-World Use Cases
Logging Data to File
file, _ := os.OpenFile("app.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
defer file.Close()
file.WriteString("Application started\n")This pattern is commonly used in applications to store logs without overwriting previous entries.
Writing API Response to File
response := "API response data"
os.WriteFile("response.txt", []byte(response), 0644)This is useful when debugging APIs or saving responses for later processing.
Creating Config or Output Files
config := []byte("port=8080\nenv=production")
os.WriteFile("config.txt", config, 0644)This approach is used to generate configuration files, reports, or output data dynamically.
Common Errors and Fixes
Permission Denied Error
This error occurs when the program does not have sufficient permissions to create or write to a file.
err := os.WriteFile("/root/file.txt", []byte("data"), 0644)In this case, writing to /root may fail if the program is not running with elevated privileges.
To fix this issue, ensure that:
- The file path is writable by the current user
- Correct file permissions are set (e.g.,
0644) - The directory exists and allows write access
Using a safe location like the current working directory or /tmp can help avoid permission-related issues.
File Not Created Issue
Sometimes the file is not created because the required flag is missing.
file, err := os.OpenFile("file.txt", os.O_WRONLY, 0644)Here, the file will not be created if it does not already exist.
To fix this, include the os.O_CREATE flag:
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY, 0644)This ensures that the file is created if it is missing.
Data Not Appended Properly
Data may overwrite existing content instead of appending if the append flag is not used.
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_WRONLY, 0644)In this case, writing will overwrite existing data.
To fix this, use the os.O_APPEND flag:
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)This ensures that new content is always added to the end of the file.
Frequently Asked Questions
1. How do you write to a file in Golang?
You can write to a file in Golang using os.WriteFile for simple operations or os.OpenFile with flags for more control.2. How do you append to a file in Golang?
You can append to a file using os.OpenFile with the os.O_APPEND flag to ensure new data is added without overwriting existing content.3. How do you create a file if it does not exist in Go?
Use os.OpenFile with the os.O_CREATE flag to create a file if it does not already exist.4. What is the difference between os.WriteFile and os.OpenFile?
os.WriteFile is used for simple file writes, while os.OpenFile provides more control using flags such as append, create, and write modes.5. What are file flags in Golang?
File flags such as os.O_CREATE, os.O_WRONLY, and os.O_APPEND control how files are opened and written in Go.Summary
Golang provides simple and efficient ways to create, write, read, and append to files using the os package.
Use os.WriteFile for quick file writes, os.OpenFile for more control with flags, and choose the appropriate method depending on whether you want to overwrite or append data. Understanding file permissions, flags, and proper usage patterns helps in avoiding common errors and building reliable applications.


