Create Text File
Create new folder named src. In src folder, create new folder named data. In data folder, create new text file named product.csv as below:
p01,name 1,4.5,20
p02,name 2,7,11
p03,name 3,2,8
Application
In src folder, create new file named main.go as below:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
file, err := os.Open("data/product.csv")
if err != nil {
fmt.Println(err)
} else {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
result := strings.Split(line, ",")
fmt.Println("id: ", result[0])
fmt.Println("name: ", result[1])
fmt.Println("price: ", result[2])
fmt.Println("quantity: ", result[3])
fmt.Println("-------------------")
}
}
file.Close()
}
Output
Open Terminal windows in Visual Studio Code and run command line: go run main.go
id: p01
name: name 1
price: 4.5
quantity: 20
-------------------
id: p02
name: name 2
price: 7
quantity: 11
-------------------
id: p03
name: name 3
price: 2
quantity: 8
-------------------