Lesson 34 of 60 · Go
File System Operations with `os` and `io/ioutil`
Duration: 15 minutes
FS Helpers
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Create, read, write, and delete files.
// Write a file
err := os.WriteFile("out.txt", []byte("hello"), 0644)
// Read a file
data, err := os.ReadFile("out.txt")
// Append to a file
f, _ := os.OpenFile("out.txt", os.O_APPEND|os.O_WRONLY, 0644)
defer f.Close()
f.WriteString("\nmore")
Directory traversal
dir, _ := os.ReadDir(".")
for _, entry := range dir {
fmt.Println(entry.Name(), entry.IsDir())
}
Temporary files
tmp, _ := os.CreateTemp("", "prefix-*.tmp")
defer os.Remove(tmp.Name())