Working with Files
Read and write text files using Go.
Learning objective: Write text to a file and read it back into the program.
Writing Files
Go can create and write files using functions from the os package.
Reading Files
The os.ReadFile function reads the contents of a file into memory.
Handling File Errors
File operations can fail because of missing files, permissions, or invalid paths. Always check errors.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import (
"fmt"
"os"
)
func main() {
data := []byte("Learning Go is practical and fun!")
err := os.WriteFile("message.txt", data, 0644)
if err != nil {
fmt.Println("Write error:", err)
return
}
content, err := os.ReadFile("message.txt")
if err != nil {
fmt.Println("Read error:", err)
return
}
fmt.Println(string(content))
}
Key points to remember
- Use []byte when writing text with os.WriteFile.
- The 0644 value is a common file permission for readable text files.
- Convert file content to string before printing it as text.
Practice Exercises
- Write your name into a text file.
- Read the file and print its content.
- Handle file errors properly.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.