Class CSV

Handles CSV file.

Summary

Return typeFunction and summary
CSVnew(string fileName, string rw, int encoding, int lineBreak)
Create a CSV object, open the file.
boolcanRead()
Is it possible to read?
boolcanWrite()
Is it possible to write?
 close()
Close the file
MapreadLine()
Read a line and return a map of column name (header) to value, nil if end of file is reached.
Mapselect(string idField, function filterFunction)
Read the whole CSV file, filter results and return a Map idField -> line (line is a Map column->value)
 writeHeader(string columnName)
In Write mode, add header if no data were already written
 writeLine(data)
Writes a line of data.

Methods

CSV:new(string fileName, string rw, int encoding, int lineBreak)

Create a CSV object, open the file.

As the file is opened, you must call :close() method once reading/writing is finished.

ParameterTypeDefaultDescription
fileNamestring The CSV file that will be read or written
rwstring "r" for read, "w" for write access.
encodingintUTF8_STR_ENCODINGCharacter encoding
lineBreakintUNKNOWN_CR for read, WIN_CR for writeLine break
Return
CSV: The CSV object
Error
if file open fails

CSV:close()

Close the file

CSV:canRead()

Is it possible to read?

Return
bool: true if file is not closed and was open in read mode.

CSV:canWrite()

Is it possible to write?

Return
bool: true if file is not closed and was open in write mode.

CSV:writeHeader(string columnName)

In Write mode, add header if no data were already written

ParameterTypeDefaultDescription
columnNamestring Column name
Errors
if file is closed or was not opened in write mode
if datas was already added
if columnName is empty or nil or already exists

CSV:writeLine(data)

Writes a line of data.

If data is a table or a Collection, it's iterated untile the number of header is reached.
If Map, datas are picked in Map according to header order.
In all cases, missing data are inserted as empty strings

ParameterTypeDefaultDescription
data  A table, Collection or Map
Errors
if file is closed or was not opened in write mode
if no header was written before
if data is nil or unrecognized type.

CSV:readLine()

Read a line and return a map of column name (header) to value, nil if end of file is reached.

Return
Map: The line of data in Map columnName->value, or nil if end of file is reached.

CSV:select(string idField, function filterFunction)

Read the whole CSV file, filter results and return a Map idField -> line (line is a Map column->value)

ParameterTypeDefaultDescription
idFieldstring#One of column used as key, or # for the row number
filterFunctionfunctionnilA function receiving each line (as a Map), returing true to include, false to exclude in results.
Return
Map: Key sorting is not guaranteed