Golang : Skip blank/empty lines in CSV file and trim whitespaces example

Tags : golang csv trim-whitespaces reader fieldsPerRecord TrimLeadingSpace


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?


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 (

 func main() {
  csvDataWithEmptyLines := `first_name,last_name,username
 "Adam","Sandler", adam

 Steve, McQueen,steve
  csvReader := csv.NewReader(strings.NewReader(csvDataWithEmptyLines))

  // add these
  csvReader.FieldsPerRecord = -1
  csvReader.TrimLeadingSpace = true

  for {
 record, err := csvReader.Read()
 if err == io.EOF {
 if err != nil {



// properly formatted and look nice

[firstname lastname username]

[Adam Sandler adam]

[Steve McQueen steve]

[Robert Spacey robspacy]



  See also : Golang : How to read CSV file

Tags : golang csv trim-whitespaces reader fieldsPerRecord TrimLeadingSpace

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.