banner



How to Read Csv File in Go Language

Reading a simple CSV in Go

Ankur Raina

In this article, you'll learn how to read a simple csv file & parse it using built-in libraries of Go. While doing this, you'll also understand the type of data that the function expects and how it is served by the other elements. While this is easy, the new beginners in Go may find some trouble in understanding how the interfaces are satisfied.

We will write the entire code in main.go

1. Open the file

Different ways of opening/reading files are explained in gobyexample.

In this case, we are going to use os.Open() which takes a string (path of the file) and returns a file descriptor.

          func Open(name string) (*File, error)        

2. Read the file

We want to use this file descriptor to read the contents. For this, we could use the bufio.NewReader() which has the below signature.

          func NewReader(rd io.Reader) *Reader        

It accepts a parameter rd (name not important) of type io.Reader. io.Reader is an interface which expects a Read method. As effective go states, if something can do this, then it can be used here which means that anything which has a Read method of the same signature can be passed as a parameter to NewReader function of bufio.

          type Reader interface {
Read(p []byte) (n int, err error)
}

We have *Filewhich was returned by the os.Open method. This File struct has the Read method which we need to satisfy the io.Reader interface.

          func (f *File) Read(b []byte) (n int, err error)        

The method bufio.NewReader() returns a pointer to Reader struct which implements buffering for an io.Readerobject. Thus, we could pass the file descriptor returned from os.Open() to bufio.NewReader(). However, we will skip this step.

3. Parse the file as csv

We will use the built-in library encoding/csv to do this task. The function csv.NewReader() returns a Reader which under the hood wraps the bufio.NewReader() that we discussed above.

          // NewReader returns a new Reader that reads from r.          func NewReader(r io.Reader) *Reader {                      return &Reader{                      Comma: ',',                      r:     bufio.NewReader(r),                      }          }        

Notice that this by default uses comma , for separation. We can change the separator using this if required.

4. Read the records

Reading the records from the returned csv reader above is easy and detailed in this example in documentation. We use a for loop to iterate on the reader using the Read method; processing (in this case printing on the standard output using fmt.Printf()) one record at a time.

The break condition is based on End of File (EOF) from the io library which is returned as an error. If the error is not EOF and is also not nil, we call log.Fatal to raise a fatal error as it suggests that something wrong happened while reading the csv file.

You'll see the below output:

          $ go run prework.go
Question: 5+5 Answer 10
Question: 1+1 Answer 2
Question: 8+3 Answer 11
Question: 1+2 Answer 3
Question: 8+6 Answer 14
Question: 3+1 Answer 4
Question: 1+4 Answer 5
Question: 5+1 Answer 6
Question: 2+3 Answer 5
Question: 3+3 Answer 6
Question: 2+4 Answer 6
Question: 5+2 Answer 7

Note:

  • I may have used the terms function and method interchangeably. I suggest reading this StackOverflow link for clarity.
  • The csv file has been taken from the first exercise Quiz Game of Gophercises

Edit on 28/07:

  • From "A Tour of Go", the difference in terms function vs method is clear. A method is a function with a special receiver argument.

How to Read Csv File in Go Language

Source: https://ankurraina.medium.com/reading-a-simple-csv-in-go-36d7a269cecd

0 Response to "How to Read Csv File in Go Language"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel