CSV(???)
Neil Cerutti
horpner at yahoo.com
Fri Feb 23 13:13:10 EST 2007
On 2007-02-23, David C Ullrich <ullrich at math.okstate.edu> wrote:
> Is there a csvlib out there somewhere?
>
> And/or does anyone see any problems with
> the code below?
>
> What csvline does is straightforward: fields
> is a list of strings. csvline(fields) returns
> the strings concatenated into one string
> separated by commas. Except that if a field
> contains a comma or a double quote then the
> double quote is escaped to a pair of double
> quotes and the field is enclosed in double
> quotes.
>
> The part that seems somewhat hideous is
> parsecsvline. The intention is that
> parsecsvline(csvline(fields)) should be
> the same as fields. Haven't attempted
> to deal with parsecsvline(data) where
> data is in an invalid format - in the
> intended application data will always
> be something that was returned by
> csvline. It seems right after some
> testing... also seems blechitudinous.
>
> (Um: Believe it or not I'm _still_ using python 1.5.7. So
> comments about iterators, list comprehensions, string methods,
> etc are irrelevent. Comments about errors in the algorithm
> would be great. Thanks.)
Two member functions of indexedstring are not used: next and
lookahead. __len__ and __getitem__ appear to serve no real
purpose.
> def parsecsvline(csvline):
> """Inverts csvline(). Assumes csvline is valid, ie
> is something as returned by csvline(); output undefined
> if csvline is in invalid format"""
>
> s = indexedstring(csvline)
> res = []
>
> while not s.eos():
> res.append(s.getfield())
>
> return res
You'll be happy to know that iterators and list comprehensions
will make your code better after you upgrade. ;-)
In the meantime, I think your (relative lack of) error handling
is OK. GIGO, as they say (garbage in, garbage out).
--
Neil Cerutti
More information about the Python-list
mailing list