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.
CSV is a pure data format without any formatting. It's a plain text file after all. So no, there is no way of adding colour.
No and No! CSV files are basically raw cell data, with no formatting at all. Open Document Format (. ods) — can be read by Excel 2010.
Steps for writing a CSV file First, open the CSV file for writing ( w mode) by using the open() function. Second, create a CSV writer object by calling the writer() function of the csv module. Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.
Open the CSV file in Microsoft Excel or a compatible application, such as a text editor or Notepad. Move your cursor to an empty line and type an H in column A. Press the Tab key to move to the next column and enter the value that you want to import for that field. Repeat step b for all the fields in the row.
Second, create a CSV writer object by calling the writer () function of the csv module. Third, write data to CSV file by calling the writerow () or writerows () method of the CSV writer object. Finally, close the file once you complete writing data to it.
To write pandas dataframe to a CSV file in Python, use the to_csv () method. At first, let us create a dictionary of lists − d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22'] }
Reading CSV Files With csv. Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python’s built-in open () function, which returns a file object. This is then passed to the reader, which does the heavy lifting. Here’s the employee_birthday.txt file:
For the first part, processing multiple CSV's as one data set, you can read in each CSV file in a loop into a list or pandas Dataframe. Then you can use .append () to add everything into a single new list or Dataframe, so you can process it all at once.
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:
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With