readCSV function

Future readCSV(
  1. String fileName,
  2. {String delimiter = ';',
  3. int skipHeader = 0,
  4. int skipFooter = 0,
  5. bool convertToArray2d = false,
  6. Encoding encoding = utf8}
)

.. 1 "nupyio". https://github.com/numpy/numpy/blob/v1.16.1/numpy/lib/npyio.py#L1536-L2219. Retrieved 2019-07-26. .. 2 "read csv file by dart". https://flutterframework.com/read-csv-file-by-dart/. Retrieved 2019-07-26. .. 3 "how to stream a file line by line in dart". https://stackoverflow.com/questions/20815913/how-to-stream-a-file-line-by-line-in-dart. Retrieved 2019-07-26. .. 4 "Dart file class". https://api.dartlang.org/stable/2.4.0/dart-io/File-class.html. Retrieved 2019-07-26. Examples

var data = await readCSV('stock_data.csv', delimiter: ',', skipHeader: 1, skipFooter: 1);

Implementation

Future<dynamic> readCSV(String fileName,
    {String delimiter = ';',
    int skipHeader = 0,
    int skipFooter = 0,
    bool convertToArray2d = false,
    Encoding encoding = utf8}) async {
  final lines = await readLinesTxt(fileName, encoding: encoding);
  var data = <List>[];

  for (var l = skipHeader; l < lines.length - skipFooter; l++) {
    // Process results.
    List rows = lines[l].split(delimiter); // split by delimiter
    var rows2 = [];
    for (var row in rows) {
      var aux = num.tryParse(row);
      rows2.add(aux ?? row);
    }
    data.add(rows2);
  }

  if (convertToArray2d) {
    var dataArray2d = Array2d.empty();

    for (var row in data) {
      var arrayRow = Array.empty();
      row.forEach((i) => arrayRow.add(i));
      dataArray2d.add(arrayRow);
    }

    return dataArray2d;
  } else {
    return data;
  }
}