Ns getcsv

From AOLserver Wiki
Jump to navigation Jump to search


ns_getcsv - Read CSV data from a file


ns_getcsv fp varName


ns_getcsv reads one line of CSV data from the specified file pointer (such as returned by the Tcl command open) and sets the variable specified by varName to a list of the elements in that row. Any double quotes in the line of data are removed. ns_getcsv returns the number of elements in the row.
If there are no more lines in the file to read, varName does not get set, and ns_getcsv returns -1 as the number of elements in the row.
A CSV file is an ASCII file containing rows of data in the following syntax:
  • Elements in each row must be separated by commas.
  • Each row must end with either \n, \r, or \r\n.
  • Elements that contain commas must be surrounded by double quotes (e.g., "foo,bar").
  • If an element surrounded by double quotes also contains a double quote, you can escape the interior double quote by using two double quotes (e.g., "Evander ""Real Deal"" Holyfield")
  • White space that isn't inside double quotes is ignored. For example, the line: 'bob, sarah, mary' will result in the list {bob sarah mary}.
  • Null entries are okay, either embedded in the line or at the end of a line. For example, the line: 'bob,,sarah, ' will result in the list: {bob {} sarah {}}.


ns_getcsv is about 10 times faster than tcllib ::csv::split but currently doesn't support delimiters other than comma and only supports double-quotes, not single-quotes. Neither one properly supports csv files with newlines inside elements



Category Documentation - Category Core Tcl API