在Python中将彩色输出写入CSV文件
我有一个程序可以使用Python中的CSV模块将内容写入CSV文件.我的要求是,如果满足给定条件,则以彩色显示文本.有没有人指出如何使用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?
感谢您的帮助.
谢谢! MSH.
您应该为此使用excel文件,因为csv文件只是纯文本文件,无法在其中保留任何颜色格式.基本上,只有当在Excel中打开CSV文件时,它才可能看起来需要格式化.
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.
无论如何,我的建议是为此尝试使用 xlsxwriter
包.您可以使用简单的pip install XlsxWriter
来安装它.
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
.
我已经为您创建了一个示例脚本,以帮助您入门.您会注意到,我有一行创建格式: 粗体 ,带有font-size
red .仅当单元格值(cell_data
)等于"xyz"
时才使用该格式.
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()
您应该得到:
我希望这会有所帮助.