Skip to content

Instantly share code, notes, and snippets.

@harryhanYuhao
Last active February 5, 2024 20:10
Show Gist options
  • Save harryhanYuhao/382ff50a75f007819aa0090268f34563 to your computer and use it in GitHub Desktop.
Save harryhanYuhao/382ff50a75f007819aa0090268f34563 to your computer and use it in GitHub Desktop.
go read/write csv
import (
"encoding/csv"
"log"
"os"
)
func readCsvFile(filePath string) [][]string {
f, err := os.Open(filePath)
if err != nil {
log.Fatal("Unable to read input file "+filePath, err)
}
defer f.Close()
csvReader := csv.NewReader(f)
records, err := csvReader.ReadAll()
if err != nil {
log.Fatal("Unable to parse file as CSV for "+filePath, err)
}
return records
}
func saveCsvFile(filePath string, record [][]string) error {
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal("Fail to create" + filePath)
}
defer f.Close()
csvWriter := csv.NewWriter(f)
defer csvWriter.Flush()
err = csvWriter.WriteAll(record)
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment