Chapter 8. CSV Recipes
8.0 Introduction
The CSV (comma-separated values) format is a file format in which tabular data (numbers and text) can be easily written and read in a text editor. CSV is widely supported, and most spreadsheet programs, such as Microsoft Excel and Apple Numbers, support CSV. Consequently, many programming languages, including Go, come with libraries that produce and consume the data in CSV files.
It might surprise you that CSV has been around for more than 50 years. The IBM Fortran compiler supported it in OS/360 back in 1972. If you’re not quite sure what that is, OS/360 is the batch processing operating system developed by IBM for its System/360 mainframe computer. So yes, one of the first uses for CSV was for Fortran in an IBM mainframe computer.
CSV is not very standardized, and not all CSV formats are separated by commas, either. Sometimes it can be a tab or a semicolon or other delimiters. However, there is an RFC specification for CSV—RFC 4180, though not everyone follows that standard.
The Go standard library has an encoding/csv package that supports RFC 4180 and helps you read and write CSV.
8.1 Reading the Whole CSV File
Problem
You want to read a CSV file into memory for use.
Solution
Use the encoding/csv package and csv.ReadAll to read all data in the CSV file into a 2D array of strings.
Discussion
Say you have a file like this:
id,first_name,last_name,email 1,Sausheong,Chang,sausheong@email.com 2,John,Doe,john@email.com
The first row ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access