csv module strangeness.

Fredrik Lundh fredrik at pythonware.com
Wed Aug 30 16:55:28 EDT 2006


tobiah wrote:

> The docs are a little terse, but I gather that I am supposed
> to subclass cvs.Dialect:
> 
> class dialect(csv.Dialect):
>         pass
> 
> Now, the docs say that all of the attributes have reasonable
> defaults, but instantiating the above gives:

you may be misreading the docs; the Dialect has no values at all, and 
must be subclassed (and the subclass must provide settings).  The 
easiest way to do get reasonable defaults is to subclass an existing
dialect class, such as csv.excel:

     class dialect(csv.excel):
         ...

 > The only thing that I can think of to do is to set
 > these on the class itself before instantiation:

the source code for the Dialect class that you posted shows how to set 
class attributes; simple assign them inside the class statement!

     class dialect(csv.excel):
         # like excel, but with a different delimiter
         delimiter = "|"

you must also remember to pass the dialect to the reader:

     reader = csv.reader(open('list.csv'), dialect)
     for row in reader:
         print row

note that you don't really have to create an instance; the reader 
expects an object with a given set of attributes, and the class object 
works as well as an instance of the same class.

</F>




More information about the Python-list mailing list