Odd csv column-name truncation with only one column

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jul 19 08:08:48 EDT 2012


On Thu, 19 Jul 2012 06:21:58 -0500, Tim Chase wrote:

> tim at laptop:~/tmp$ python
> Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import csv
>>>> from cStringIO import StringIO
>>>> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') s.seek(0)
>>>> d = csv.Sniffer().sniff(s.read())
>>>> s.seek(0)
>>>> r = csv.DictReader(s, dialect=d)
>>>> r.fieldnames
> ['Emai', '']


I get the same results for Python 2.6 and 2.7. Curiously, 2.5 returns 
fieldnames as None.

I'm not entirely sure that a single column is legitimate for CSV -- if 
there's only one column, it is hardly comma-separated, or any other 
separated for that matter. But perhaps the csv module should raise an 
exception in that case.

I think you've found a weird corner case where the sniffer goes nuts. You 
should probably report it as a bug:

py> s = StringIO('Email\nfoo at example.com\nbar at example.org\n')
py> s.seek(0)
py> d = csv.Sniffer().sniff(s.read())
py> d.delimiter
'l'

py> s = StringIO('Spam\nfoo at example.com\nbar at example.org\n')
py> s.seek(0)
py> d = csv.Sniffer().sniff(s.read())
py> d.delimiter
'p'

py> s = StringIO('Spam\nham\ncheese\n')
py> s.seek(0)
py> d = csv.Sniffer().sniff(s.read())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/csv.py", line 184, in sniff
    raise Error, "Could not determine delimiter"
_csv.Error: Could not determine delimiter


-- 
Steven



More information about the Python-list mailing list