read_csv.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // read_csv.go
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "strconv"
  10. "strings"
  11. )
  12. type Book struct {
  13. title string
  14. price float64
  15. quantity int
  16. }
  17. func main() {
  18. bks := make([]Book, 1)
  19. file, err := os.Open("products.txt")
  20. if err != nil {
  21. log.Fatalf("Error %s opening file products.txt: ", err)
  22. }
  23. defer file.Close()
  24. reader := bufio.NewReader(file)
  25. for {
  26. // read one line from the file:
  27. line, err := reader.ReadString('\n')
  28. readErr := err
  29. // remove \r and \n so 2(in Windows, in Linux only \n, so 1):
  30. line = string(line[:len(line)-2])
  31. //fmt.Printf("The input was: -%s-", line)
  32. strSl := strings.Split(line, ";")
  33. book := new(Book)
  34. book.title = strSl[0]
  35. book.price, err = strconv.ParseFloat(strSl[1], 32)
  36. if err != nil {
  37. fmt.Printf("Error in file: %v", err)
  38. }
  39. //fmt.Printf("The quan was:-%s-", strSl[2])
  40. book.quantity, err = strconv.Atoi(strSl[2])
  41. if err != nil {
  42. fmt.Printf("Error in file: %v", err)
  43. }
  44. if bks[0].title == "" {
  45. bks[0] = *book
  46. } else {
  47. bks = append(bks, *book)
  48. }
  49. if readErr == io.EOF {
  50. break
  51. }
  52. }
  53. fmt.Println("We have read the following books from the file: ")
  54. for _, bk := range bks {
  55. fmt.Println(bk)
  56. }
  57. }
  58. /* Output:
  59. We have read the following books from the file:
  60. {"The ABC of Go" 25.5 1500}
  61. {"Functional Programming with Go" 56 280}
  62. {"Go for It" 45.900001525878906 356}
  63. {"The Go Way" 55 5}
  64. */