~/Working with CSV Data in Go
Feb 9, 2024
Go provides robust support for handling CSV data via its encoding/csv package.
Reading CSV
To read a CSV file, use csv.NewReader and Read or ReadAll.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import (
"encoding/csv"
"os"
)
file, err := os.Open("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
// records is a [][]string containing CSV rows
|
Writing CSV
To write data to CSV, use csv.NewWriter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import (
"encoding/csv"
"os"
)
file, err := os.Create("output.csv")
if err != nil {
panic(err)
}
defer file.Close()
writer := csv.NewWriter(file)
err = writer.Write([]string{"header1", "header2"})
if err != nil {
panic(err)
}
writer.WriteAll([][]string{
{"value1", "value2"},
{"value3", "value4"},
})
writer.Flush()
|
Considerations
- Strings are always read and written as []string slices.
- Use strconv for type conversion.
- Handle csv.Reader.Comma if your file uses delimiters other than comma.
For advanced CSV processing, libraries like gocarina/gocsv can simplify working with structs.