dlang

DLANG : read a CSV file with the standard CSV library (std.csv)

The D language (DLANG) provides a standard library to read CSV files. Unfortunately, the documentation does not show any examples which reads a file. Instead, the documentation shows how to use the CSV library from a string. It’s not very useful since we always read CSV format from files rather than string variables …

Anyway, since there are very few examples of DLANG (D language) code on Internet, I am going to explain how I managed to read properly a CSV file with the std.csv lib and stock line values into an associative array.


module CsvExample;

import std.csv;
import std.stdio;
import std.stream;
import std.string;

class CsvExample {
	this(){}
	void main(string[] args){

		// steam used to read our CSV file. parFilePath is a string parameter containing the absolute path to our CSV file
		BufferedFile locBufferedFile = new BufferedFile(parFilePath);

		// where we stock the CSV header string
		char[] locHeaderLine;

		// used as a HashMap to stock a string key and its string value
		string[string] locLocaleValues;

		//loop on all the file lines
		foreach(ulong i, char[] locLine; locBufferedFile) {

			// write current line to stdout to debug
			writefln("processing line %d: %s", i, locLine);

			// we are reading the first line : we keep the headers in the locHeaderLine variable
			if(i == 1){
				locHeaderLine = locLine.dup;

			// we are reading a csv line with content
			} else {

				// we create a CSV string with headers so we can use properly the standard CSV api
				// this is the only way I found to have the CSV API working
				char[] locCsvToProcess = locHeaderLine ~ '\n' ~ locLine ~ '\n';

				// use the standard CSV library to get records of our current line. In our header
				auto records = csvReader!KeyValue(locCsvToProcess, ["key","fr_FR"]);

				foreach(record; records) {
					writefln("key: %s value: %s", record.key, record.value);

					// stock key-value in the associative array (map)
					locLocaleValues[record.key] = record.value.dup;

				}

			}

		}
		// don't forget to close the stream
		locBufferedFile.close();
	}
}

I am sure there is a better way to do this. Line 37 is not very nice but it’s the only way I managed to have a good string which can be parsed by the call on line 40.

It’s also my first try with DLANG so the code might not be very nice.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>