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
// 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:
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
// 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:
Fig 1.2
Similar Reads
How to Read and Write the Files in Golang? Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file. This revised version reflects the changes made in
4 min read
How to Read File Word By Word in Golang? File reading is such an important aspect of a programming language. We need to perform certain operations programmatically, using automation in file reading/writing allows us to create certain programs/projects which might have looked impossible otherwise. File InputTo work with files, we have to in
5 min read
How to Access Interface Fields in Golang? Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a varia
3 min read
How to Create an Empty File in Golang? Like other programming languages, Go language also allows you to create files. For creating a file it provides Create() function, this function is used to create or truncates the given named file. This method will truncate the file, if the given file is already exists. This method will create a file
2 min read
How to Read a File Line by Line to String in Golang? To read a file line by line the bufio package Scanner is used. Let the text file be named as sample.txt and the content inside the file is as follows: GO Language is a statically compiled programming language, It is an open-source language. It was designed at Google by Rob Pike, Ken Thompson, and Ro
2 min read
How to append a slice in Golang? In Go, slices are dynamically-sized, flexible views into the elements of an array. Appending elements to a slice is a common operation that allows for the expansion of the slice as needed. The built-in append function is used to add elements to the end of a slice.In this article,we will learn How to
2 min read
How to Create Modules in Golang? Go has included support for versioned modules as proposed here since 1.11 with the initial prototype as vgo. The concept of modules in Go was introduced to handle the problem of dependencies within your Go applications. Several packages are collected and combined to form a module which is stored in
3 min read
How to Find Indirect Dependency in Golang? Go, also known as Golang, is a statically typed, compiled language with a rich standard library and a robust ecosystem of packages. When building Go applications, itâs common to use third-party packages to avoid reinventing the wheel. However, these packages can have their own dependencies, known as
4 min read
How to Trim a String in Golang? In Go, strings are UTF-8 encoded sequences of variable-width characters, unlike some other languages like Java, python and C++. Go provides several functions within the strings package to trim characters from strings.In this article we will learn how to Trim a String in Golang.Examples := "@@Hello,
2 min read
How to Replace Characters in Golang String? In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to replace characters in the given string usin
4 min read