CSV Parser and unusual (?) linesterminator - misunderstanding?

Tino Lange Tino.Lange at is-teledata.com
Fri Jan 20 03:52:36 EST 2006


Hi!

I'm trying to use the csv Parser included with Python. Field Delimiter is
"|", Line Delimiter is "#". Unfortunately it doesn't work as expected. The
parser seems to just ignore the 'lineterminator'?

Here's some example:

> $ cat test.py
> #! /usr/bin/env python
> 
> import sys, csv, cStringIO
> 
> class SpecialCSVDialect(csv.Dialect):
>     delimiter = '|'
>     lineterminator = '#'
>     quotechar = '"'
>     doublequote = True
>     skipinitialspace = False
>     quoting = csv.QUOTE_MINIMAL
> 
> csv.register_dialect("SpecialCSV", SpecialCSVDialect)
> 
> memfile = cStringIO.StringIO("1a|1b|1c|1d#2a|2b|2c|2d#3a|3b|3c|3d#")
> cfile = csv.reader(memfile, dialect="SpecialCSV")
> 
> while 1:
>   try:
>     data = cfile.next()
>   except csv.Error, (errmsg):
>     print >> sys.stderr, "SpecialCSVError '%s' - aborting...!" % (errmsg)
>     sys.exit()
>   except StopIteration:
>     break
>   print data

> $ ./test.py
> ['1a', '1b', '1c', '1d#2a', '2b', '2c', '2d#3a', '3b', '3c', '3d#']
> $

I would have been expecting that the parser returns three lines, i. e. 

> ['1a', '1b', '1c', '1d']
> ['2a', '2b', '2c', '2d']
> ['3a', '3b', '3c', '3d']

Any hints what I'm doing wrong here?

Thanks

Tino



More information about the Python-list mailing list