~/File Operations in Golang

Mar 14, 2019


Go provides os and io/ioutil packages for file operations. Common tasks include creating, reading, writing, and deleting files.

Create a file:

1
2
3
4
5
6
import "os"
f, err := os.Create("file.txt")
if err != nil {
    // handle error
}
defer f.Close()

Write to a file:

1
f.WriteString("Hello, Go\n")

Read a file:

1
2
3
4
5
6
import "io/ioutil"
data, err := ioutil.ReadFile("file.txt")
if err != nil {
    // handle error
}
fmt.Print(string(data))

Delete a file:

1
err := os.Remove("file.txt")

For advanced usage and file info, see os.FileInfo and bufio packages. Always check errors to avoid resource leaks and unexpected issues.

Tags: [golang] [files] [io]