package main import ( "encoding/csv" "os" ) func main() { file, err := os.Create("example.csv") if err != nil { panic(err) } defer file.Close() writer := csv.NewWriter(file) data := [][]string{{"Name", "Age", "Country"}, {"Alice", "25", "USA"}, {"Bob", "30", "Canada"}} for _, record := range data { err = writer.Write(record) if err != nil { panic(err) } } writer.Flush() }
package main import ( "encoding/csv" "fmt" "os" ) func main() { file, err := os.Open("example.csv") if err != nil { panic(err) } defer file.Close() reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { panic(err) } fmt.Println(records) writer := csv.NewWriter(os.Stdout) writer.WriteAll(records) writer.Flush() }In this example, we read an existing CSV file using the csv.Reader and print the parsed records to the console. Then, we create a new csv.Writer and write all the records to the console using WriteAll. Finally, we call Flush to ensure that all the data gets written to the console.