Python CSV formatting with string and float and write


How do you format a float to 2 decimal points with mixed data type? I'm fetching a table and writing rows to csv file. My data is (string, string, float, float, float...)

    sql = 'select * from testTable'

    columnNames = list(map(lambda x: x[0], c.description))
    result = c.fetchall()

    with open(outputCSVPath, 'wb') as f:
        writer = csv.writer(f)

With the above code, I get floats with 6 decimal places. I need to format it to 2 decimal places but because of the first 2 of the list being string, it gives me an type error.

Thank you.

You can iterate the result in order to parse only the floats values, and then you can use writer.writerows(row) to write row by row. Take a look here to know the different ways to iterate your results.

On the other hand, you can format floats to two decimals points using the round() function from python.

An example:

>>> # Each of your rows should be something like:
>>> list = ["string1", "string3", 1.435654, 4.43256]

>>> #Round the floats
>>> parsed_list = [round(x, 2) if i > 1 else x for i, x in enumerate(list)]

>>> print parsed_list
['string1', 'string2', 1.44, 4.43]