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.4k Golang : Write multiple lines or divide string into multiple lines
+12.9k Golang : zlib compress file example
+12.2k Golang : Decompress zlib file example
+24.2k Golang : Find biggest/largest number in array
+14.6k Golang : Find network of an IP address
+7.4k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+8.4k Golang : Qt splash screen with delay example
+13.7k Golang : Read from buffered reader until specific number of bytes
+31.8k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+17.8k Convert JSON to CSV in Golang
+32.8k Golang : Copy directory - including sub-directories and files
+17.2k Golang : Get the IPv4 and IPv6 addresses for a specific network interface