forked from joncrlsn/go-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv.go
More file actions
68 lines (57 loc) · 1.2 KB
/
csv.go
File metadata and controls
68 lines (57 loc) · 1.2 KB
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
//
// An example of how to process a csv files
//
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"strings"
)
func main() {
fmt.Println("=== csv ===")
ReadData()
WriteArray()
}
func WriteArray() {
fmt.Println("Write: ===")
records := [][]string{
{"first_name", "last_name", "username"},
{"Rob", "Pike", "rob"},
{"Ken", "Thompson", "ken"},
{"Robert", "Griesemer", "gri"},
}
w := csv.NewWriter(os.Stdout)
for _, record := range records {
if err := w.Write(record); err != nil {
log.Fatalln("error writing record to csv:", err)
}
}
// Write any buffered data to the underlying writer (standard output).
w.Flush()
if err := w.Error(); err != nil {
log.Fatal(err)
}
}
func ReadData() {
fmt.Println("Read: ===")
// The first line is the title line
const in = `
"Group","Title","Username","Password","URL","Notes"
"Root","Peterson Family Tree","joncrlsn","more-secret-than-you-know","http://www.example.com/phpgedview/",""
"Root","Twitter","jon_carlson","supersecret","http://twitter.com",""
`
r := csv.NewReader(strings.NewReader(in))
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(record)
}
}