Thomas Kremmel
Thomas Kremmel

Reputation: 14783

python csv - export data and format color, text format, etc

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?

Upvotes: 3

Views: 6476

Answers (2)

dalloliogm
dalloliogm

Reputation: 8940

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.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

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.

Upvotes: 3

Related Questions