# The states of the parser StartRecord = 0 StartField = 1 InField = 2 QuoteInField = 3 InQuotedField = 4 QuoteInQuotedField = 5 EndQuotedField = 6 # State handlers can return Finished to terminate parsing early Finished = 10 class ParseError(Exception): pass class CSVParser: """ Parses CSV files including all subtleties such as: * commas in fields * double quotes in fields * embedded newlines in fields - Examples of programs that produce such beasts include MySQL and Excel For a higher-level, friendlier CSV class with many conveniences, see DataTable (which uses this class for its parsing). Example: records = [] parse = CSVParser().parse for line in lines: results = parse(line) if results is not None: records.append(results) CREDIT The algorithm was taken directly from the open source Python C-extension, csv: http://www.object-craft.com.au/projects/csv/ It would be nice to use the csv module when present, since it is substantially faster. Before that can be done, it needs to support allowComments and stripWhitespace, and pass the TestCSVParser.py test suite. """ def __init__(self, allowComments=1, stripWhitespace=1, fieldSep=',', autoReset=1, doubleQuote=1): """ @@ document """ # settings self._allowComments = allowComments self._stripWhitespace = stripWhitespace self._doubleQuote = doubleQuote self._fieldSep = fieldSep self._autoReset = autoReset # Other self._state = StartRecord self._fields = [] self._hadParseError = 0 self._field = [] # a list of chars for the cur field self.addChar = self._field.append # The handlers for the various states self._handlers = [ self.startRecord, self.startField, self.inField, self.quoteInField, self.inQuotedField, self.quoteInQuotedField, self.endQuotedField, ] ## Parse ## def parse(self, line): """ Parse the single line and return a list or string fields, or None if the CSV record contains embedded newlines and the record is not yet complete. """ if self._autoReset and self._hadParseError: self.reset() handlers = self._handlers i = 0 lineLen = len(line) while i