Created
September 2, 2024 18:07
-
-
Save alexandreliberato/f853dcdddd68815e66058f5688a4cc46 to your computer and use it in GitHub Desktop.
Reading CSV file in Go with multiple delimiters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/csv" | |
| "fmt" | |
| "io" | |
| "log" | |
| "strings" | |
| ) | |
| func main() { | |
| csvData := `col1;col2,col3 | |
| value1;value2,value3 | |
| value4;value5,value6` | |
| reader := csv.NewReader(strings.NewReader(csvData)) | |
| // Set the delimiter to be a function that splits on both ';' and ',' | |
| reader.Comma = ';' | |
| reader.FieldsPerRecord = -1 // Allow variable number of fields | |
| for { | |
| record, err := reader.Read() | |
| if err == io.EOF { | |
| break | |
| } | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| for i, field := range record { | |
| if i < len(record)-1 && strings.Contains(field, ",") { | |
| subfields := strings.Split(field, ",") | |
| record = append(record[:i+1], append(subfields, record[i+1:]...)...) | |
| } | |
| } | |
| fmt.Println(record) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment