Last active
February 5, 2024 20:10
-
-
Save harryhanYuhao/382ff50a75f007819aa0090268f34563 to your computer and use it in GitHub Desktop.
go read/write csv
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
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