Last active
April 27, 2019 16:14
-
-
Save koyo-miyamura/10d2efdac1b787c6cb8582763e127e89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id | name | age | |
---|---|---|---|
1 | koyo | 24 | |
2 | maimai | 23 | |
3 | tomozo | 20 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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