Back to Course
File Handling

File Handling in Go – Read, Write, and Parse JSON/CSV Files

Reading a File

data, err := os.ReadFile("data.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))

Writing a File

err := os.WriteFile("output.txt", []byte("Hello, Go!"), 0644)

Parsing JSON

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

var u User
data, _ := os.ReadFile("user.json")
json.Unmarshal(data, &u)
fmt.Println(u.Name)

Parsing CSV

file, _ := os.Open("data.csv")
defer file.Close()

reader := csv.NewReader(file)
records, _ := reader.ReadAll()
for _, row := range records {
    fmt.Println(row)
}

Ready to master real-world Go skills?

Learn Go hands-on with mentor-led, live sessions.

Explore Course