csv - how to parse a string, not a file?

A

Alex Hunsley

I've using the csv module to parse a string, not a file.
So how do I make a string look like a file so I can call csv.reader()
with it?

An an example, I'd like to call something like:

csvReader = csv.reader("1,2,3,4")

... but this direct attempt won't work as it expects a file or a handle...

thanks
alex
 
J

John Lenton

I've using the csv module to parse a string, not a file.
So how do I make a string look like a file so I can call csv.reader()
with it?

An an example, I'd like to call something like:

csvReader = csv.reader("1,2,3,4")

.. but this direct attempt won't work as it expects a file or a handle...

what is cStringIO?
 
A

Alex Hunsley

John said:
sorry; I should stop giving answers as questions.

Oh, that was an answer! Sorry! I thought you were a newbie who had tried to
post a new topic but had just hit 'reply' or something like that...
 
J

James Henderson

Much thanks! That does the job nicely..
alex

I know this suggestion comes a bit late but

csvReader = csv.reader("1,2,3,4".splitlines(1))

may be a bit more efficient. csv.reader() does not actually require a
file-like object - any iterable will do, such as a list. The docstring is
explicit about this even though the online docs imply that the "csvfile"
object must have a next() method.

James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,661
Latest member
sxarexu

Latest Threads

Top