How to Read a CSV File in Golang?
Last Updated :
26 Apr, 2023
Golang offers a vast inbuilt library that can be used to perform read and write operations on files. To read a CSV file, the following methods are used in Golang:
- os.Open(): The os.Open() method opens the named file for reading. This method returns either the os.File pointer or an error.
- encoding/csv: This package provides a NewReader function which is used to read a CSV file and it returns a *csv.Reader which is further used to read the contents of the file as a series of records.
Note: Use the offline compiler for better results. Save the program file with .go extension. Use the below command to execute the program:
go run filename.go
Example 1: Let us consider the CSV file named Students.csv and the contents inside the file are as follows:
S001,Thomas Hardy,CS01
S002,Christina Berglund,CS05
S003,Yang Wang,CS01
S004,Aria Cruz,CS05
S005,Hanna Moos,CS01
Below is the Golang program to read a CSV file:
Go
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open( "Students.csv" )
if err != nil {
log.Fatal( "Error while reading the file" , err)
}
defer file.Close()
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil
{
fmt.Println( "Error reading records" )
}
for _, eachrecord := range records
{
fmt.Println(eachrecord)
}
}
|
Output:
Fig 1.1
One can also provide a custom separator to read CSV files instead of a comma(,), by defining that in Reader struct.
Reader structure returned by NewReader function
type Reader struct{
// Comma is field delimiter set to (,) by NewReader
// which can be changed to custom delimeter
// but it must be a valid rune and it should
// not be \r,\n or unicode replacement character (0xFFFD).
Comma rune
Comment rune
FieldsPerRecord int
LazyQuotes bool
TrimLeadingSpace bool
ReuseRecord bool
TrailingComma bool
}
Example 2: Below example shows how to read a CSV file that has a custom separator. Let the CSV file be named Sample.csv and the contents in the file are as follows:
Word1-Word2
Word3-Word4
Word5-Word6
Below is the Golang program to read a CSV file with a custom separator:
Go
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open( "Sample.csv" )
if err != nil {
log.Fatal( "Error while reading the file" , err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = '-'
records, err := reader.ReadAll()
if err != nil
{
fmt.Println( "Error reading records" )
}
for _, eachrecord := range records
{
fmt.Println(eachrecord)
}
}
|
Output:
Fig 1.2
Share your thoughts in the comments
Please Login to comment...