Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Can you write a go program to read a csv file of lines containing "date,open stock…

  1. User

    Can you write a go program to read a csv file of lines containing "date,open stock price, last price" ?

  2. 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
    }
    

    Make sure to replace the "stocks.csv" in the os.Open() function with the path to your actual CSV file.

    This program opens the CSV file, validates the column names are correct, and then loops through the data lines, printing the date, open stock price, and last price for each line.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.