Writing Files in Go
Go: Writing Files
In Go, writing files can be achieved using the os package, which provides various functions to create, open, write and close files.
How to write to a file in Go:
package main
import (
"fmt"
"os"
)
func main() {
// Create or open the file
file, err := os.Create("example.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close() // Close the file when done
// Write some data to the file
_, err = file.WriteString("Hello, World!")
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
}
Explaination:
we first create a file called example.txt using the os.Create function. We check if an error occurred during the file creation process, and if so, we return and print the error message.
After creating the file, we defer its closing to ensure it gets closed once we're done writing to it.
Finally, we write the string "Hello, World!" to the file using the file.WriteString function. Again, we check if an error occurred during the writing process, and if so, we return and print the error message.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go