Golang : Skip blank/empty lines in CSV file and trim whitespaces example
Problem:
Your Golang program is reading from a CSV file and you want to skip blank lines in the CSV file. Also, you want to trim whitespaces in the final output. How to do that?
Solution:
After initiating the csv.Read()
or csv.NewReader()
functions. Set the reader's FieldsPerRecord
and TrimLeadingSpace
to:
csvReader.FieldsPerRecord = -1 // optional
csvReader.TrimLeadingSpace = true
The CSV reader will automagically ignore those empty lines.
Here you go!
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"strings"
)
func main() {
csvDataWithEmptyLines := `first_name,last_name,username
"Adam","Sandler", adam
Steve, McQueen,steve
"Robert","Spacey","robspacy"
`
csvReader := csv.NewReader(strings.NewReader(csvDataWithEmptyLines))
// add these
csvReader.FieldsPerRecord = -1
csvReader.TrimLeadingSpace = true
for {
record, err := csvReader.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(record)
}
}
Output:
// properly formatted and look nice
[firstname lastname username]
[Adam Sandler adam]
[Steve McQueen steve]
[Robert Spacey robspacy]
References:
See also : Golang : How to read CSV file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.9k Golang : convert string or integer to big.Int type
+20.4k Golang : Convert seconds to minutes and remainder seconds
+8.9k Golang : Channels and buffered channels examples
+5.8k CloudFlare : Another way to get visitor's real IP address
+6k Golang : How to detect if a sentence ends with a punctuation?
+44.1k Golang : Read tab delimited file with encoding/csv package
+6.8k Golang : Error reading timestamp with GORM or SQL driver
+5.1k AWS S3 : Prevent Hotlinking policy
+10.7k Golang : md5 hash of a string
+18.3k Golang : Close channel after ticker stopped example
+28.4k Golang : How to verify uploaded file is image or allowed file types
+8.5k Golang : Format strings to SEO friendly URL example