gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Can you write a go program to read a csv file of lines containing "date,open stock…
- User
Can you write a go program to read a csv file of lines containing "date,open stock price, last price" ?
- Assistant
Certainly! Here's an example Go program that reads a CSV file containing lines with "date,open stock price,last price" structure and prints the data:
package main import ( "encoding/csv" "fmt" "io" "log" "os" ) func main() { // Open the CSV file file, err := os.Open("stocks.csv") if err != nil { log.Fatal(err) } defer file.Close() // Create a new CSV reader reader := csv.NewReader(file) // Read the column names columns, err := reader.Read() if err != nil { log.Fatal(err) } // Validate the column names expectedColumns := []string{"date", "open stock price", "last price"} if !equalSlices(columns, expectedColumns) { log.Fatalf("Invalid column names. Expected: %v, Received: %v", expectedColumns, columns) } // Read and process the data lines for { line, err := reader.Read() if err == io.EOF { break } else if err != nil { log.Fatal(err) } fmt.Printf("Date: %s\nOpen Stock Price: %s\nLast Price: %s\n\n", line[0], line[1], line[2]) } } func equalSlices(a, b []string) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true }