How to Read a CSV File in Golang?
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
// Go program to illustrate // How to read a csv file package main import ( "encoding/csv" "fmt" "log" "os" ) func main() { // os.Open() opens specific file in // read-only mode and this return // a pointer of type os.File file, err := os.Open( "Students.csv" ) // Checks for the error if err != nil { log.Fatal( "Error while reading the file" , err) } // Closes the file defer file.Close() // The csv.NewReader() function is called in // which the object os.File passed as its parameter // and this creates a new csv.Reader that reads // from the file reader := csv.NewReader(file) // ReadAll reads all the records from the CSV file // and Returns them as slice of slices of string // and an error if any records, err := reader.ReadAll() // Checks for the error if err != nil { fmt.Println( "Error reading records" ) } // Loop to iterate through // and print each of the string slice for _, eachrecord := range records { fmt.Println(eachrecord) } } |
Output:
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
// Golang program to illustrate // How to read a csv file with // custom separator package main import ( "encoding/csv" "fmt" "log" "os" ) func main() { // os.Open() opens specific file in // read-only mode and this return // a pointer of type os.File file, err := os.Open( "Sample.csv" ) // Checks for the error if err != nil { log.Fatal( "Error while reading the file" , err) } // Closes the file defer file.Close() // The csv.NewReader() function is called in // which the object os.File passed as its parameter // and this creates a new csv.Reader that reads // from the file reader := csv.NewReader(file) // To specify the custom separator use the // following syntax // Comma is the field delimiter. By default it is // set to comma (',') by NewReader. // Comma must be a valid rune (int32) and must not be // \r, \n, or the Unicode replacement character (0xFFFD). reader.Comma = '-' // ReadAll reads all the records from the CSV file and // Returns them as slice of slices of string and an // error if any records, err := reader.ReadAll() // Checks for the error if err != nil { fmt.Println( "Error reading records" ) } // Loop to iterate through // and print each of the string slice for _, eachrecord := range records { fmt.Println(eachrecord) } } |
Output: