Tag Archives: csv
How to split a string csv-style in Python
So, this is easy:
>>> ‘foo,bar’.split(’,')
[’foo’, ‘bar’]
But here’s the problem:
>>> "foo,bar,’spam,eggs’".split(’,')
[’foo’, ‘bar’, "’spam", "eggs’"]
Sometimes you want a csv-style split without the hassle of actually using Python’s otherwise excellent full-blown csv parser module.
So I wrote something that lets you do this:
>>> from csvsplit import csvsplit
>>> csvsplit(’foo,bar,"spam,eggs"’)
[’foo’, ‘bar’, ’spam,eggs’]
>>> csvsplit(’foo,bar,"spam,eggs"’, delimiter=’\t’)
[’foo,bar,"spam,eggs"’]
>>> csvsplit(’foo\tbar\t"spam\t\teggs"’, delimiter=’\t’)
[’foo’, ‘bar’, ’spam\t\teggs’]
Download it here. Enjoy!