Last active
October 26, 2021 12:37
-
-
Save manju4ever/7645bdd14896c8f82b64e4be97db866d to your computer and use it in GitHub Desktop.
Read CSV From Go
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 ( | |
"fmt" | |
"os" | |
"github.com/gocarina/gocsv" | |
) | |
/* users.csv | |
ID,first_name,last_name,email | |
1,manjunath,desappa,[email protected] | |
2,rob,langdon,[email protected] | |
*/ | |
type User struct { | |
ID string `csv:"ID"` | |
FirstName string `csv:"first_name"` | |
LastName string `csv:"last_name"` | |
Email string `csv:"email"` | |
NotUsed string `csv:"-"` | |
} | |
func ReadUsersFromCSV(filePath string) []*User { | |
userFile, err := os.OpenFile(filePath, os.O_RDWR, os.ModePerm) | |
if err != nil { | |
panic(err) | |
} | |
defer userFile.Close() | |
usersList := []*User{} | |
if err := gocsv.Unmarshal(userFile, &usersList); err != nil { | |
panic(err) | |
} | |
for _, userData := range usersList { | |
fmt.Printf("$%v\n", userData) | |
} | |
return usersList | |
} | |
func printHelper() { | |
fmt.Println(`Usage: tcompare <user summary> <user transcript>`) | |
} | |
func main() { | |
args := os.Args[1:] | |
if args[0] == "--help" { | |
printHelper() | |
return | |
} | |
users := ReadUsersFromCSV(args[0]) | |
fmt.Println("Found:", len(users)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment