Source file
src/encoding/csv/example_test.go
1
2
3
4
5 package csv_test
6
7 import (
8 "encoding/csv"
9 "fmt"
10 "io"
11 "log"
12 "os"
13 "strings"
14 )
15
16 func ExampleReader() {
17 in := `first_name,last_name,username
18 "Rob","Pike",rob
19 Ken,Thompson,ken
20 "Robert","Griesemer","gri"
21 `
22 r := csv.NewReader(strings.NewReader(in))
23
24 for {
25 record, err := r.Read()
26 if err == io.EOF {
27 break
28 }
29 if err != nil {
30 log.Fatal(err)
31 }
32
33 fmt.Println(record)
34 }
35
36
37
38
39
40 }
41
42
43
44 func ExampleReader_options() {
45 in := `first_name;last_name;username
46 "Rob";"Pike";rob
47 # lines beginning with a # character are ignored
48 Ken;Thompson;ken
49 "Robert";"Griesemer";"gri"
50 `
51 r := csv.NewReader(strings.NewReader(in))
52 r.Comma = ';'
53 r.Comment = '#'
54
55 records, err := r.ReadAll()
56 if err != nil {
57 log.Fatal(err)
58 }
59
60 fmt.Print(records)
61
62
63 }
64
65 func ExampleReader_ReadAll() {
66 in := `first_name,last_name,username
67 "Rob","Pike",rob
68 Ken,Thompson,ken
69 "Robert","Griesemer","gri"
70 `
71 r := csv.NewReader(strings.NewReader(in))
72
73 records, err := r.ReadAll()
74 if err != nil {
75 log.Fatal(err)
76 }
77
78 fmt.Print(records)
79
80
81 }
82
83 func ExampleWriter() {
84 records := [][]string{
85 {"first_name", "last_name", "username"},
86 {"Rob", "Pike", "rob"},
87 {"Ken", "Thompson", "ken"},
88 {"Robert", "Griesemer", "gri"},
89 }
90
91 w := csv.NewWriter(os.Stdout)
92
93 for _, record := range records {
94 if err := w.Write(record); err != nil {
95 log.Fatalln("error writing record to csv:", err)
96 }
97 }
98
99
100 w.Flush()
101
102 if err := w.Error(); err != nil {
103 log.Fatal(err)
104 }
105
106
107
108
109
110 }
111
112 func ExampleWriter_WriteAll() {
113 records := [][]string{
114 {"first_name", "last_name", "username"},
115 {"Rob", "Pike", "rob"},
116 {"Ken", "Thompson", "ken"},
117 {"Robert", "Griesemer", "gri"},
118 }
119
120 w := csv.NewWriter(os.Stdout)
121 w.WriteAll(records)
122
123 if err := w.Error(); err != nil {
124 log.Fatalln("error writing csv:", err)
125 }
126
127
128
129
130
131 }
132
View as plain text