sexta-feira, 20 de dezembro de 2019

Python3 - String data as csv (file or list) objects

I spent the last three days reading Python guides, manuals, blogs, tutorials, e-books, etc. just to be able to start working with data in text format I gathered from sensors and text format tables.

I got stuck because I was incorrectly trying to use csv methods to manipulate a file that I read into a string, and wrongly though I could just format it as a standard csv file layout.  This just does not work!

The official doc for csv.reader() at https://docs.python.org/2/library/csv.html is very helpful, which stats this:

    "file objects and list objects are both suitable"

The solution is to convert your formatted string to a "file or list object", (what ?!?)

The side effect of not doing this is that all csv methods don't fetch the items correctly and ignores your delimiters (ie. like the comma)

So you have two ways of doing this:

First:  you can import StringIO to perform this conversion:

   from IO import StringIO
   import csv


After that you need to code the conversion, and for this example lets assume your string is named: target

   new_csv = StringIO(target)

But wait!!! Hold your horses!!! Keep on reading.

Second: Or choose a easier way, that is: make a list from your string:

   new_csv = target.splitlines()

You can check the type of objects with:

   print('type of target  = '+str(type(target)))
   print('type of new_csv = '+str(type(new_csv)))

Now you are ready to use all the csv methods to analise/manipulate your tables/data

Cheers!

Nenhum comentário:

Postar um comentário