【问题标题】:writing colored output into CSV file in Python在 Python 中将彩色输出写入 CSV 文件
【发布时间】:2017-05-06 02:50:46
【问题描述】:

我有一个程序可以使用 Python 中的 CSV 模块将内容写入 CSV 文件。如果满足给定条件,我的要求是用彩色显示文本。有没有人指点如何使用 CSV 模块来实现这一点?

感谢您的帮助。

谢谢! MSH。

【问题讨论】:

  • CSV 文件没有颜色格式。您一定在考虑使用 Excel 打开的 csv 文件。在 Excel 中打开 CSV 文件时,它只是一个纯文本文件,着色实际上是由 Excel 完成的。底线是:使用 excel 文件和 python 的 excel 包。
  • 您能否分享一个您希望将其内容传输到 Excel 文件的起始文件?
  • @Abdou :很遗憾知道 CSV 不支持这一点。我可以尝试使用 excel 包。这是我写入 csv 的示例内容:{"1":["xyz",""],"2":["abc","def"],"3":["zzz", ""]}。键是标题,值是内容。假设我想根据某些条件以红色突出显示文本“xyz”。

标签: python-2.7 export-to-csv


【解决方案1】:

您应该为此使用 excel 文件,因为 csv 文件只是纯文本文件,无法在其中保留任何颜色格式。基本上,只有在 Excel 中打开 CSV 文件时才会出现格式化。

无论如何,我的建议是您尝试为此使用xlsxwriter 包。您可以使用简单的pip install XlsxWriter 安装它。

我为您创建了一个示例脚本来帮助您入门。您会注意到我有一行创建格式:boldfont-sizered。该格式仅在单元格值 (cell_data) 等于 "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()

你应该得到:

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2023-03-11
    相关资源
    最近更新 更多