python将输出结果写入csv,在Python中将彩色输出写入CSV文件

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.

解决方案

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:

wrbcX.png

I hope this helps.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值