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
+9.7k Golang : Check if user agent is a robot or crawler example
+3.5k Java : Random alphabets, alpha-numeric or numbers only string generator
+11.1k Golang : Characters limiter example
+9.1k Golang : Terminate-stay-resident or daemonize your program?
+10.4k Golang : How to delete element(data) from map ?
+3.8k Detect if Google Analytics and Developer Media are loaded properly or not
+13.2k Golang : Count number of runes in string
+4.4k Adding Skype actions such as call and chat into web page examples
+25k Golang : Convert long hexadecimal with strconv.ParseUint example
+22.4k Golang : Strings to lowercase and uppercase example
+9.1k Golang : Find the length of big.Int variable example