Last active
August 18, 2023 16:16
-
-
Save miguelmota/0a3f3339141f336833ecd62de1e8539b to your computer and use it in GitHub Desktop.
Golang CSV write example
This file contains 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" | |
"log" | |
"os" | |
) | |
func main() { | |
records := [][]string{ | |
{"first_name", "last_name", "username"}, | |
{"Rob", "Pike", "rob"}, | |
{"Ken", "Thompson", "ken"}, | |
{"Robert", "Griesemer", "gri"}, | |
} | |
w := csv.NewWriter(os.Stdout) | |
for _, record := range records { | |
if err := w.Write(record); err != nil { | |
log.Fatalln("error writing record to csv:", err) | |
} | |
} | |
// Write any buffered data to the underlying writer (standard output). | |
w.Flush() | |
if err := w.Error(); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use
bytes.NewBuffer
to write to a bytes buffer: