Go programs can handle CSV. Comma-separated values files are a form of flat databases. They can store small amounts of information in an efficient way.
With Go and the "encoding/csv" package, we can read lines from CSV files. We can invoke, from the "os" package, a method like os.Open
to specify a file.
Here we open a file on the disk with os.Open
. You will need to change the path to a CSV file that exists (the extension is not important).
csv.NewReader
method. We use Read()
and test EOF.Println
. Then we use len
to determine the number of values in each record.package main import ( "bufio" "encoding/csv" "os" "fmt" "io" ) func main() { // Load a TXT file. f, _ := os.Open("C:\\programs\\file.txt") // Create a new reader. r := csv.NewReader(bufio.NewReader(f)) for { record, err := r.Read() // Stop at EOF. if err == io.EOF { break } // Display record. // ... Display record length. // ... Display all individual elements of the slice. fmt.Println(record) fmt.Println(len(record)) for value := range record { fmt.Printf(" %v\n", record[value]) } } }cat,dog,bird 10,20,30,40 fish,dog,snake[cat dog bird] 3 cat dog bird [10 20 30 40] 4 10 20 30 40 [fish dog snake] 3 fish dog snake
ReadAll
, stringsWe can read lines from a string
. First we must use strings.NewReader
and use the string
as the argument. We pass that Reader to csv.NewReader
.
ReadAll
consumes the entire CSV Reader's data at once. We then can use a for
-loop to iterate over the lines.ReadAll
. We use an underscore variable name to discard the error.package main import ( "encoding/csv" "fmt" "strings" ) func main() { // Create a 2-line string. data := " fish,blue,water \n fox,red,farm " // Use strings.NewReader. // ... This creates a new Reader for passing to csv.NewReader. r := csv.NewReader(strings.NewReader(data)) // Read all records. result, _ := r.ReadAll() fmt.Printf("Lines: %v", len(result)) fmt.Println() for i := range result { // Element count. fmt.Printf("Elements: %v", len(result[i])) fmt.Println() // Elements. fmt.Println(result[i]) } }Lines: 2 Elements: 3 [ fish blue water ] Elements: 3 [ fox red farm ]
With ReadAll
we receive a 2D slice of lines and the values within each line. We can use len
to count elements in a line. With append()
we can add to this 2D slice.
Why not just use a Scanner and Split
each line in a file? The csv package can help us avoid some code. We can reuse the code provided in the Go standard library.
The "encoding/csv" package is powerful. We set options on the Reader to handle different formats of files. We read CSV values from a file on the disk.