I like CSV files for their portability (Python, Excel), ease of debug, and lightweight nature (no SQL databases etc). However, one key aspect of CSV files is that they are column-oriented–that is, you have to keep track of which data is in which column.
In python, csv.DictReader
and csv.DictWriter
do this for you–you don’t have to keep track of which data is in which column; the reader/writer does this for you.
I was looking for something similar in Matlab, so that I can read CSV files. In Matlab, the structure array is ideal for this, as it lets you create an array (one record per row) with structured data (one field per column).
The following file is something I wrote to read in CSV data. It returns a structure array, where the field names are given by a header line in the CSV file. It supports both numeric and string data in the CSV fields, with one caveat: all text-valued fields must occur contiguously and be the first columns in the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function [ S ] = csv_struct_read( file_name ) %csv_strct_read: S = csv_struct_read( file_name ) % Read CSV file, with headers, as a struct array % Header fields are struct fields. Dimension of % struct array is NR x 1 where NR is number of % non-header lines (rows) in CSV. A = importdata(file_name, ',', 1); if size(A.textdata, 1) > 1 D = A.textdata(2:end, :); D(strcmp(D, '')) = num2cell(A.data); S = cell2struct(D, A.textdata(1,:), 2); else S = cell2struct(num2cell(A.data), A.colheaders, 2); end end |