Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary?
I don't think I want the built in csv module because in all the examples I've seen that takes filepaths, not strings.
Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary?
I don't think I want the built in csv module because in all the examples I've seen that takes filepaths, not strings.
Simple - the csv module works with lists, too:
As others have already pointed out, Python includes a module to read and write CSV files. It works pretty well as long as the input characters stay within ASCII limits. In case you want to process other encodings, more work is needed.
The Python documentation for the csv module implements an extension of csv.reader, which uses the same interface but can handle other encodings and returns unicode strings. Just copy and paste the code from the documentation. After that, you can process a CSV file like this:
https://docs.python.org/2/library/csv.html?highlight=csv#csv.reader
Thus, a
StringIO.StringIO()
,str.splitlines()
or even a generator are all good.The official doc for
csv.reader()
https://docs.python.org/2/library/csv.html is very helpful, which saysPanda is quite powerful and smart library reading CSV in Python
A simple example here, I have example.zip file with four files in it.
Once you have data you can manipulate to play with a list or other formats.
I would use
StringIO
:simplier version with
split()
on newlines:Or you can simply
split()
this string into lines using\n
as separator, and thensplit()
each line into values, but this way you must be aware of quoting, so usingcsv
module is preferred.