golang统计csv数据

1.需求说明
最近由于需要统计csv文件内某个数据的值,故使用golang写了个小程序来实现此功能

2.设计知识点
a.文件操作
b.读取一行内容

3.代码

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "os"
    "strconv"
    "strings"
)

func calcAverageValue(path string) (float64, error) {
    f, err := os.Open(path)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    fReader := bufio.NewReader(f)
    i := -1
    var counts float64
    var sums float64
    sums = 0.0
    counts = 0.0
    for {
        line, err := fReader.ReadBytes('\n')
        if err != nil || io.EOF == err {
            break
        }
        i++
        if i < 1 {
            continue
        }
        strLine := string(line)
        strArray := strings.Split(strLine, ",")
        if len(strArray) <= 1 {
            continue
        }
        f, _ := strconv.ParseFloat(strArray[6], len(strArray[6]))
        sums += f
        counts++
    }

    if counts == 0 {
        return 0.0, err
    }
    av := sums / counts * 1.0

    return av, nil
}

func main() {

    commonFilePath := "./data/PA"
    for i := 1; i < 11; i++ {
        path := commonFilePath + strconv.Itoa(i)
        path += ".csv"
        av, e := calcAverageValue(path)
        if e != nil {
            log.Fatal(e)
        }
        fmt.Printf("file:%s ,result: %f\n", path, av)
    }
}

结果如图
golang统计csv数据_第1张图片

你可能感兴趣的:(Go学习)