golang csv 解析

golang 操作csv文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main

import (
"bytes"
"encoding/csv"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
)

var (
fileName = "test.csv"
mode string
)

type Book struct {
Author string
Title string
}

func (book *Book) toSlice() []string {
return []string{book.Author, book.Title}
}

func toCSV(lines [][]string, w io.Writer) error {
n := csv.NewWriter(w)
for _, line := range lines {
err := n.Write(line)
if err != nil {
return err
}
}
n.Flush()
return n.Error()
}

func writeCSV() error {
// init
books := []Book{
Book{
Author: "F Scott Fitzgerald",
Title: "The Great Gatsby",
},
Book{
Author: "J D Salinger",
Title: "The Catcher in the Rye",
},
}

var items [][]string
for _, book := range books {
items = append(items, book.toSlice())
}

buffer := new(bytes.Buffer)
if err := toCSV(items, buffer); err != nil {
return err
}

// save to files
f, err := os.Create(fileName)
defer f.Close()
if err != nil {
return err
}
_, err = f.WriteString(buffer.String())

return err
}

func readCSV() error {
f, err := ioutil.ReadFile(fileName)
if err != nil {
return err
}
buffer := bytes.NewBufferString(string(f))

csvReader := csv.NewReader(buffer)
csvReader.Comma = ';'
csvReader.Comment = '-'

records, err := csvReader.ReadAll()
if err != nil {
return err
}

fmt.Println(records)
return nil
}

func main() {
flag.StringVar(&mode, "mode", "", "read/write csv file")
flag.Parse()

switch mode {
case "write":
writeCSV()
case "read":
readCSV()
default:
flag.Usage()
}
}

欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 qinhan_shu@163.com

文章标题:golang csv 解析

本文作者:QinHan

发布时间:2019-10-22, 12:08:43

最后更新:2020-02-20, 05:42:12

原始链接:https://qinhan.site/2019/10/22/go-csv/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏