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
+30k Golang : How to get HTTP request header information?
+11.9k Golang : convert(cast) float to string
+12.1k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+12.4k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+9.2k Golang : Intercept and compare HTTP response code example
+14.3k Elastic Search : Mapping date format and sort by date
+7.6k Golang : Rot13 and Rot5 algorithms example
+20k Golang : Measure http.Get() execution time
+9k Golang : Gaussian blur on image and camera video feed examples
+25.8k Golang : missing Mercurial command
+12.6k Golang : Arithmetic operation with numerical slices or arrays example
+7.5k Golang : Hue, Saturation and Value(HSV) with OpenCV example