Section 7 of 12
File I/O & Packages
Working with files and organizing code with packages
Course Progress
Section 7 of 1258% complete
Tutorials
File Operations
Go provides powerful file handling capabilities through the os and io packages.
Code Examples
Read & Write Filesgo
package main
import (
"fmt"
"os"
"io/ioutil"
)
func main() {
// Write to file
data := []byte("Hello, Go!\n")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
fmt.Println(err)
}
// Read from file
content, err := os.ReadFile("output.txt")
if err != nil {
fmt.Println(err)
}
fmt.Println(string(content))
// Read line by line
file, _ := os.Open("output.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}Packages & Imports
Go organizes code into packages. Every Go file belongs to a package, enabling code reuse and organization.
Code Examples
Creating Packagesgo
// math/operations.go
package math
func Add(a, b int) int {
return a + b
}
func Subtract(a, b int) int {
return a - b
}
// main.go
package main
import (
"fmt"
"myapp/math"
)
func main() {
result := math.Add(5, 3)
fmt.Println(result)
}Exercises
CSV File Reader
Create a program to read and parse CSV files
INTERMEDIATEStarter Code:
package main
import (
"fmt"
"encoding/csv"
"os"
)
func main() {
// TODO: Read and parse CSV file
}Hands-on Project
Log File Analyzer
Analyze log files and generate reports
INTERMEDIATE
Learning Objectives
- >File I/O
- >Data parsing
- >Report generation
Project Tips
- > Start by understanding the requirements
- > Break the project into smaller tasks
- > Test your code frequently as you build
- > Add error handling throughout your code
- > Consider edge cases and validate inputs
- > Document your code with comments