Go File Handling
Reading, writing, and managing files in Go
📁 What is File Handling in Go?
File handling in Go allows you to read, write, create, and manage files on your system. Go provides powerful built-in packages like os and io for efficient file operations.
// Simple file reading example
package main
import (
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(data))
}
Output:
Contents of example.txt file
Essential File Operations
Reading Files
Read entire files or line by line
data, err := os.ReadFile("file.txt")
Writing Files
Create and write content to files
err := os.WriteFile("file.txt", data, 0644)
File Info
Get file properties and metadata
info, err := os.Stat("file.txt")
File Management
Delete, rename, and move files
err := os.Remove("file.txt")
🔹 Reading Files
Go provides multiple ways to read files:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Method 1: Read entire file
data, err := os.ReadFile("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("File content:", string(data))
// Method 2: Read line by line
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println("Line:", scanner.Text())
}
}
Output:
File content: Hello, Go File Handling!
Line: Hello, Go File Handling!
🔹 Writing Files
Create and write content to files easily:
package main
import (
"fmt"
"os"
)
func main() {
// Write string to file
content := "Hello, Go!\nThis is file handling."
err := os.WriteFile("output.txt", []byte(content), 0644)
if err != nil {
fmt.Println("Error writing file:", err)
return
}
fmt.Println("File written successfully!")
// Append to file
file, err := os.OpenFile("output.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
_, err = file.WriteString("\nAppended line!")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Content appended!")
}
Output:
File written successfully!
Content appended!
🔹 File Information
Get detailed information about files:
package main
import (
"fmt"
"os"
"time"
)
func main() {
info, err := os.Stat("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("File name:", info.Name())
fmt.Println("Size:", info.Size(), "bytes")
fmt.Println("Mode:", info.Mode())
fmt.Println("Modified:", info.ModTime().Format(time.RFC3339))
fmt.Println("Is directory:", info.IsDir())
}
Output:
File name: example.txt
Size: 25 bytes
Mode: -rw-r--r--
Modified: 2024-01-15T10:30:00Z
Is directory: false