How to read csv file in golang?

by august.kutch , in category: Golang , 2 years ago

How to read csv file in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@august.kutch You can import encoding/csv and csv.NewReader() to read csv file in Golang, below is code as example:


 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
package main

import (
   "encoding/csv"
   "fmt"
   "os"
)

func main() {

   path := "/tmp/test.csv"
   file, err := os.Open(path)

   if err != nil {
      panic(err)
   }

   defer file.Close()

   reader := csv.NewReader(file)
   rows, err := reader.ReadAll()
   if err != nil {
      panic(err)
   }

   for _, row := range rows {
      fmt.Println(row)
   }
}
by cassandra , 10 months ago

@august.kutch 

To read a CSV file in Golang, follow the below steps:

  1. Open the CSV file:
1
2
3
4
5
file, err := os.Open("filename.csv")
if err != nil {
    log.Fatal(err)
}
defer file.Close()


  1. Create a CSV reader:
1
reader := csv.NewReader(file)


  1. Read the CSV data:
1
2
3
4
data, err := reader.ReadAll()
if err != nil {
    log.Fatal(err)
}


The ReadAll() function returns all the CSV data as a slice of slices. Each row is represented as a slice of strings.

  1. Parse the CSV data:


Parse the CSV data according to your requirements. For example, you can iterate over the rows and columns of the data and do some operation like print or write to a database.


Here is an example code that reads a CSV file and prints its data:

 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
package main

import (
    "encoding/csv"
    "log"
    "os"
)

func main() {
    // Open CSV file
    file, err := os.Open("data.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // Create a CSV reader
    reader := csv.NewReader(file)

    // Read CSV data
    data, err := reader.ReadAll()
    if err != nil {
        log.Fatal(err)
    }

    // Print CSV data
    for _, row := range data {
        for _, col := range row {
            log.Println(col)
        }
    }
}