-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadAndWriteFile.go
56 lines (47 loc) · 1.16 KB
/
readAndWriteFile.go
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
package main
import (
"bufio"
"encoding/csv"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
// READ FILE //
filepath := "/Users/konstantin.igin/desktop/test_users.csv"
file, err := os.Open(filepath)
if err != nil {
fmt.Printf("An error occured while opening the file: %s, error: %s\n", filepath, err)
os.Exit(1)
}
defer file.Close()
var values []int
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
value, err := strconv.Atoi(line)
if err != nil {
fmt.Printf("An error occured while scanning line: %s, err: %s\n", line, err)
os.Exit(1)
}
values = append(values, value)
}
// for i, v := range values {
// fmt.Printf("%d: %d\n", i, v)
// }
// WRITE INTO CSV FILE //
outputFilepath := "/Users/konstantin.igin/desktop/users.csv"
outputFile, err := os.Create(outputFilepath)
if err != nil {
fmt.Printf("Error creating file: %s, err: %s\n", outputFilepath, err)
}
defer outputFile.Close()
writer := csv.NewWriter(outputFile)
var records [][]string
for _, val := range values {
records = append(records, []string{strconv.Itoa(val)})
}
writer.WriteAll(records)
writer.Flush()
}