The following code should help. I've commented on the relevant parts so that it's easy to understand.
package main
import (
"encoding/csv"
"os"
)
// handle error using panic
func handleError(err error) {
if err != nil {
panic(err)
}
}
// empty returns true if all fields are empty
func empty(record []string) bool {
for i := range record {
if record[i] != "" {
return false
}
}
return true
}
func main() {
in, err := os.Open("in.csv")
handleError(err)
defer in.Close()
out, err := os.Create("out.csv")
handleError(err)
defer out.Close()
r := csv.NewReader(in)
{
r.Comma = ';' // Delimiter
r.FieldsPerRecord = 0 // Number of fields should match with the header
r.TrimLeadingSpace = true // Trim the leading spaces
}
w := csv.NewWriter(out)
{
w.Comma = ';' // Delimiter
}
// Read all records
records, err := r.ReadAll()
handleError(err)
// Write records that are not empty
for _, record := range records {
if !empty(record) {
_ = w.Write(record)
}
}
// Flush records in buffer
w.Flush()
}
Input:
;Header1;Header2;Header3;
;;;;
;1;2;3;
;;;;
Output:
;Header1;Header2;Header3;
;1;2;3;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…