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
+7.6k Golang : Gaussian blur on image and camera video feed examples
+3.8k Nginx and PageSpeed build from source CentOS example
+30.1k Golang : Math pow(the power of x^y) example
+16.8k Golang : Check if a directory exist or not
+4.6k Unix/Linux/MacOSx : Get local IP address
+11k Android Studio : Highlight ImageButton when pressed on example
+18k Golang : Check if directory exist and create if does not exist
+5k Fontello : How to load and use fonts?
+14.6k Golang : How to reverse elements order in map ?
+6.2k Golang : Check if one string(rune) is permutation of another string(rune)
+14.3k Golang : invalid character ',' looking for beginning of value
+3.8k Golang : Experimental Jawi programming language