File Handling in Go (Golang)
File handling in Go is straightforward and efficient. Go provides a rich set of functions in the os
and io
packages to work with files. This section covers everything from basic file operations to advanced techniques like error handling and working with directories.
Opening a File
Use the os.Open()
function to open a file in read-only mode. Always check for errors after opening a file.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
// Read file content
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(data[:count]))
}
Writing to a File
Use the os.Create()
function to create or truncate a file, and then write to it using file.Write()
or file.WriteString()
.
package main
import (
"os"
)
func main() {
file, err := os.Create("example.txt")
if err != nil {
panic(err)
}
defer file.Close()
_, err = file.WriteString("Hello, Go!")
if err != nil {
panic(err)
}
}
Reading and Writing with ioutil
The ioutil
package provides convenient functions like ReadFile
and WriteFile
for quick file operations.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
// Reading a file
data, err := ioutil.ReadFile("example.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))
// Writing to a file
err = ioutil.WriteFile("example.txt", []byte("Hello, ioutil!"), 0644)
if err != nil {
panic(err)
}
}
File Modes
Go allows you to specify file modes when creating or opening files. Common modes include:
os.O_RDONLY
: Open for reading only.os.O_WRONLY
: Open for writing only.os.O_CREATE
: Create the file if it does not exist.os.O_APPEND
: Append data to the file.
package main
import (
"os"
)
func main() {
file, err := os.OpenFile("example.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer file.Close()
_, err = file.WriteString(" Appended text!")
if err != nil {
panic(err)
}
}
Error Handling
Always handle errors when working with files. Use the errors
package or fmt.Errorf
to create custom error messages.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("nonexistent.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
}
Working with Directories
Go provides functions to work with directories, such as os.Mkdir
, os.ReadDir
, and os.Remove
.
package main
import (
"fmt"
"os"
)
func main() {
// Create a directory
err := os.Mkdir("example_dir", 0755)
if err != nil {
panic(err)
}
// List files in a directory
files, err := os.ReadDir("example_dir")
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
// Remove a directory
err = os.Remove("example_dir")
if err != nil {
panic(err)
}
}
Best Practices
- Always Close Files: Use
defer
to ensure files are closed after operations. - Handle Errors: Check for errors after every file operation to avoid runtime issues.
- Use Buffered I/O: For large files, use buffered I/O (
bufio
) to improve performance. - Use Constants for File Modes: Use constants like
0644
for file permissions to ensure consistency. - Prefer
ioutil
for Simple Tasks: Useioutil
for quick file reads and writes when performance is not critical.