MiscUtils.CSVParser
index
/usr/local/share/webware/MiscUtils/CSVParser.py

# The states of the parser

 
Modules
       
types

 
Classes
       
CSVParser
exceptions.Exception
ParseError

 
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.
 
  Methods defined here:
__init__(self, allowComments=1, stripWhitespace=1, fieldSep=',', autoReset=1, doubleQuote=1)
@@ document
endQuotedField(self, c)
inField(self, c)
inQuotedField(self, c)
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.
quoteInField(self, c)
quoteInQuotedField(self, c)
reset(self)
Resets the parser to a fresh state in order to recover from
exceptions. But if autoReset is true (the default), this is
done automatically.
saveField(self)
startField(self, c)
startRecord(self, c)

 
class ParseError(exceptions.Exception)
     Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
Functions
       
joinCSVFields(fields)
Returns a CSV record (eg a string) from a sequence of fields.
Fields containing commands (,) or double quotes (") are quoted
and double quotes are escaped (""). The terminating newline is
NOT included.
parse(self, line) method of CSVParser instance
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.

 
Data
        EndQuotedField = 6
Finished = 10
InField = 2
InQuotedField = 4
QuoteInField = 3
QuoteInQuotedField = 5
StartField = 1
StartRecord = 0