Skip to content

Instantly share code, notes, and snippets.

@koyo-miyamura
Last active Apr 27, 2019
Embed
What would you like to do?
id name age
1 koyo 24
2 maimai 23
3 tomozo 20
package main
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"os"
"strings"
)
const path = "hoge.csv"
func main() {
fmt.Println("---fileRead()---")
fileRead(path)
fmt.Println("---bufRead()---")
bufRead(path)
fmt.Println("---csvRead()---")
csvRead(path)
// ---fileRead()---
// "id","name","age"
// 1,"koyo",24
// 2,"maimai",23
// 3,"tomozo",20
// ---bufRead()---
// "id","name","age"
// 1,"koyo",24
// 2,"maimai",23
// 3,"tomozo",20
// ---csvRead()---
// id name age
// 1 koyo 24
// 2 maimai 23
// 3 tomozo 20
}
func fileRead(path string) {
fp, err := os.Open(path)
if err != nil {
panic(err)
}
reader := bufio.NewReader(fp)
// csv.NewReader.ReadLine の返り値は []byte
for line, _, err := reader.ReadLine(); err != io.EOF; {
if err != nil && err != io.EOF {
panic(err)
}
fmt.Println(string(line))
line, _, err = reader.ReadLine()
}
}
func bufRead(path string) {
fp, err := os.Open(path)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(fp)
for scanner.Scan() {
// bufio.NewScanner.Text の返り値はText
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
func csvRead(path string) {
fp, err := os.Open(path)
if err != nil {
panic(err)
}
reader := csv.NewReader(fp)
for {
// csv.NewReader.Read の返り値は []string
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
fmt.Println(strings.Join(record, " "))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment