writing colored output into CSV file in Python
Asked Answered
S

1

7

I have a program to write content into a CSV file using CSV module in Python. My requirement is to show text in color if a given condition is satisfied. Does anyone has pointers on how to achieve this using CSV module?

Appreciate your help.

Thanks! MSH.

Spradlin answered 20/12, 2016 at 19:32 Comment(3)
A csv file does not have color formatting. You must be thinking about csv files opened with Excel. When you open a CSV file in Excel, it's just a plain text file and the coloring is actually done by Excel. Bottom line is: work with excel files and excel packages for python.Actualize
Can you please share a starting file whose content you're looking to transfer to an Excel file?Actualize
@Actualize : Sad to know that CSV doesn't support that. I can try using excel package. Here is the sample content that i'm writing into csv :{"1":["xyz",""],"2":["abc","def"],"3":["zzz",""]}. Keys are headers and values are contents. say i want to highlight text "xyz" in red based on some condition.Spradlin
A
10

You should use an excel file for this, because csv files are merely plain text files that cannot keep any coloring formatting within them. Basically, the only time a CSV file may seem like it's got formatting is when it's opened in Excel.

In any case, my recommendation is that you try using the xlsxwriter package for this. You can install it with an easy pip install XlsxWriter.

I have created a sample script for you to get you started. You will notice that I have a line that creates a formatting: bold with font-size red. That formatting is only used when a cell value (cell_data) is equal to "xyz".

from collections import OrderedDict
import xlsxwriter


data = {"1":["xyz",""],"2":["abc","def"],"3":["zzz",""]}

# Use an OrderedDict to maintain the order of the columns
data = OrderedDict((k,data.get(k)) for k in sorted(data.keys()))

# Open an Excel workbook
workbook = xlsxwriter.Workbook('dict_to_excel.xlsx')

# Set up a format
book_format = workbook.add_format(properties={'bold': True, 'font_color': 'red'})

# Create a sheet
worksheet = workbook.add_worksheet('dict_data')

# Write the headers
for col_num, header in enumerate(data.keys()):
    worksheet.write(0,col_num, int(header))

# Save the data from the OrderedDict into the excel sheet
for row_num,row_data in enumerate(zip(*data.values())):
    for col_num, cell_data in enumerate(row_data):
        if cell_data ==  "xyz":
            worksheet.write(row_num+1, col_num, cell_data, book_format)
        else:
            worksheet.write(row_num+1, col_num, cell_data)

# Close the workbook
workbook.close()

You should get:

enter image description here

I hope this helps.

Actualize answered 21/12, 2016 at 2:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.