tags:

views:

321

answers:

2

Hi,

I'm exporting data from python with the csv library which works pretty good. After a web-search I can not find any information about how to format the exported data with python.

For example. I export a csv row within python like this.

for hour_record in object_list:
            row = list()
            for field in fields:
                try:
                    row.append(getattr(hour_record, field))
                except:
                    pass
            writer.writerow(row)

Now I'm wondering how I can pass some formating information to the row.append call. For example if I want to format the text red and make sure that it is formated as a number etc..

anybody an idea how this works?

+1  A: 

CSV is used only for plain text. If you want formatting information to be contained then you must either embed HTML fragments, or you must add the attributes as separate fields. Either option will require a consumer that understands said formatting mechanism.

Ignacio Vazquez-Abrams
ok thanks. If I get you right I should use another library for exporting if I want to add formating information. e.g. an .xls library. Could you recommend a library for exporting data to excel?
Tom Tom
Some people have mentioned having good results with `xlwt`, although I've never had opportunity to use it myself.
Ignacio Vazquez-Abrams
Thanks, I will give it a try.
Tom Tom
A: 

Instead of csv, you should use numpy.genfromtxt and numpy.savetxt:

>>> data = numpy.genfromtxt('mydata.txt', dtype=None)
>>> <-> work with the data recarray object
>>> numpy.savetxt('results.txt', data)

If you look at help(numpy.savetxt) you can see that there is a 'fmt' option that allows you to specify the output format.

To output colors, you have to use HTML as said in another answer, or you can use the module terminalcolor which is only to output to STDOUT.

dalloliogm