# 08.8 读取CSV文件

`CSV`文件是纯文本文件。在本节中，你将学习如何读取包含平面点的文本文件，这意味着每一行将包含一对坐标。此外，你还将使用一个名为`Glot`的外部`Go`库，它将帮助你创建从`CSV`文件中读取的点的图表。注意，`Glot`使用`Gnuplot`，这意味着你需要在`Unix`机器上安装`Gnuplot`才能使用`Glot`。

本章的程序是`CSVplot.go`，分为五部分。第一部分代码如下：

```go
package main

import (
    "encoding/csv"
    "fmt"
    "github.com/Arafatk/glot"
    "os"
    "strconv"
)
```

`CSVplot.go`第二部分代码如下：

```go
func main() {
    if len(os.Args) != 2 {
        fmt.Println("Need a data file!")
        return
    }

    file := os.Args[1]
    _, err := os.Stat(file)
    if err != nil {
        fmt.Println("Cannot stat", file)
        return
    }
```

在本部分中，你将看到一种使用强大的`os.Stat()`函数检查文件是否已经存在的技术。

`CSVplot.go`第三部分代码如下：

```go
    f, err := os.Open(file)
    if err != nil {
        fmt.Println("Cannot open", file)
        fmt.Println(err)
        return
    }
    defer f.Close()

    reader := csv.NewReader(f)
    reader.FieldsPerRecord = -1
    allRecords, err := reader.ReadAll()
    if err != nil {
        fmt.Println(err)
        return
    }
```

`CSVplot.go`第四部分代码如下：

```go
    xP := []float64{}
    yP := []float64{}

    for _, rec := range allRecords {
        x, _ := strconv.ParseFloat(rec[0], 64)
        y, _ := strconv.ParseFloat(rec[1], 64)
        xP = append(xP, x)
        yP = append(yP, y)
    }

    points := [][]float64{}
    points = append(points, xP)
    points = append(points, yP)
    fmt.Println(points)
```

此处，你将字符串转为数字，并追加到二维切片`points`中。

`CSVplot.go`最后一部分代码如下：

```go
    dimensions := 2
    persist := true
    debug := false
    plot, _ := glot.NewPlot(dimensions, persist, debug)

    plot.SetTitle("Using Glot with CSV data")
    plot.SetXLabel("X-Axis")
    plot.SetYLabel("Y-Axis")
    style := "circle"
    plot.AddPointGroup("Circle:", style, points)
    plot.SavePlot("output.png")
}
```

在前面的`go`代码中，你了解了如何使用`Glot`库及其`Glot.SavePlot()`函数创建`PNG`文件。

可以猜到，在编译和执行`CSVplot.go`之前，需要下载`Glot Go`库，它需要从Unix shell执行以下命令：

```
$ go get github.com/Arafatk/glot
```

你可以通过查看`~/go`目录查看当前命令的执行结果:

```
$ ls -l ~/go/pkg/darwin_amd64/github.com/Arafatk/
total 240
-rw-r--r-- 1 mtsouk staff 119750 Jan 22 22:12 glot.a
$ ls -l ~/go/src/github.com/Arafatk/glot/
total 120
-rw-r--r--  1 mtsouk  staff   1818   Jan  22 22:12 README.md
-rw-r--r--  1 mtsouk  staff   6092   Jan  22 22:12 common.go
-rw-r--r--  1 mtsouk  staff    552   Jan  22 22:12 common_test.go
-rw-r--r--  1 mtsouk  staff   3162   Jan  22 22:12 core.go
-rw-r--r--  1 mtsouk  staff    138   Jan  22 22:12 core_test.go
-rw-r--r--  1 mtsouk  staff   3049   Jan  22 22:12 function.go
-rw-r--r--  1 mtsouk  staff    511   Jan  22 22:12 function_test.go
-rw-r--r--  1 mtsouk  staff   4955   Jan  22 22:12 glot.go
-rw-r--r--  1 mtsouk  staff    220   Jan  22 22:12 glot_test.go
-rw-r--r--  1 mtsouk  staff  10536   Jan  22 22:12 pointgroup.go
-rw-r--r--  1 mtsouk  staff    378   Jan  22 22:12 pointgroup_test.go
```

包含要绘制的点的`CSV`数据文件具有以下格式：

```
$ cat /tmp/dataFile
1,2
2,3
3,3
4,4
5,8
6,5
-1,12
-2,10
-3,10
-4,10
```

执行`CSVplot.go`会产生如下的输出：

```
$ go run CSVplot.go /tmp/doesNoExits
Cannot stat /tmp/doesNoExits
$ go run CSVplot.gp /tmp/dataFile
[[1 2 3 4 5 6 -1 -2 -3 -4] [2 3 3 4 8 5 12 10 10 10]]
```

你可以用下图查看`CSVplot.go`的结果。 ![""](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/images/chapter8/08.8.png)
