CSV Dialect Example Requested - NEWBIE

Peter Otten __peter__ at web.de
Tue Oct 28 07:09:07 EST 2003


caldwellinva wrote:

> Hi!
> 
>> I do not have an example, but the first failure in this script is that
>> the class in the csv module that you want to use as a base class is
>> csv.Dialect (note case). This causes the attribute error you report.
> 
> Vince, thank you for pointing this out ... it runs further now, but still
> produces an error.
> 
> Revised Version
> 
> import csv
> 
> import csv
> class dialect(csv.Dialect):
>     delimiter = '|'
>     skipinitialspace = True
>     quotechar = '"'
>     doublequote = True
> 
> reader = csv.reader(file("c:\\Temp\\test.csv"), dialect=dialect)
> for row in reader:
>      print row
> 
> Error Message
> 
> Traceback (most recent call last):
>   File
> "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
>     exec codeObject in __main__.__dict__
>   File "C:\Python23\DougSource\test_csv.py", line 10, in ?
>     reader = csv.reader(file("c:\\Temp\\test.csv"), dialect=dialect)
>   File "C:\Python23\lib\csv.py", line 39, in __init__
>     raise Error, "Dialect did not validate: %s" % ", ".join(errors)
> Error: Dialect did not validate: lineterminator not set, quoting parameter
> not set

You need these additional attributes - just read the traceback :-)

    lineterminator = '\r\n' # or probably '\n' if not on Windows
    quoting = csv.QUOTE_MINIMAL

By the way, the easiest way to get a working Dialect is to subclass
csv.excel, e. g:

class PipeDialect(csv.excel):
    delimiter = '|'

Peter




More information about the Python-list mailing list