- Open the console and create the folder chapter02/recipe10.
- Navigate to the directory.
- Create a file named data.csv with the following content:
"Name","Surname","Age"
# this is comment in data
"John","Mnemonic",20
Maria,Tone,21
- Create the data.go file with the following content:
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
file, err := os.Open("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = 3
reader.Comment = '#'
for {
record, e := reader.Read()
if e != nil {
fmt.Println(e)
break
}
fmt.Println(record)
}
}
- Run the code by executing go run data.go.
- See the output in the Terminal:
- Create a file named data_uncommon.csv with the following content:
Name;Surname;Age
"John";Mnemonic;20
"Maria";Tone;21
- Create a file named data_uncommon.go with the following content:
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
file, err := os.Open("data_uncommon.csv")
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = ';'
for {
record, e := reader.Read()
if e != nil {
fmt.Println(e)
break
}
fmt.Println(record)
}
}
- Run the code by executing go run data_uncommon.go.
- See the output in the Terminal: