Files are everywhere: logs, configs, saved game data, even text you type.
In Go, working with files is super simple.
Let’s start with the basics.
We need the os and io/ioutil or os and bufio packages for file stuff.
import (
"fmt"
"os"
"io/ioutil"
)Let’s write "Hello, Go!" into a file.
func main() {
err := ioutil.WriteFile("myfile.txt", []byte("Hello, Go!"), 0644)
if err != nil {
fmt.Println("Error writing:", err)
}
}💡 What’s 0644? That’s the file permission (like read/write). Just copy it for now.
Let’s read the file we just wrote:
func main() {
data, err := ioutil.ReadFile("myfile.txt")
if err != nil {
fmt.Println("Error reading:", err)
return
}
fmt.Println(string(data))
}It prints:
Hello, Go!What if you want to add more lines to the same file?
func main() {
f, err := os.OpenFile("myfile.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening:", err)
return
}
defer f.Close()
if _, err := f.WriteString("\nMore content here!"); err != nil {
fmt.Println("Error writing:", err)
}
}Want to remove a file?
os.Remove("myfile.txt")Poof! Gone.
Save logs
Load configuration
Store user preferences
Write and read data like CSV, JSON, etc.
Use
ioutil.WriteFile()to create/write filesUse
ioutil.ReadFile()to readUse
os.OpenFile()withO_APPENDto add more contentAlways check for errors
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.