Convert .xls to .csv using python while preserving trailing zeros

95 Views Asked by At

I want to convert my .xls file to .csv with python. In my .xls file, I have decimal values ​​with significant digits that I need to keep. For example, I have values like 27.50 and 45.550, and when I execute my script, I lose my significant digits. My values are becoming 27.5 and 45.55.

Here is my script :

import xlrd
import csv

def xls_to_csv_with_zeros(input_file, output_file):
    workbook = xlrd.open_workbook(input_file)
    sheet = workbook.sheet_by_index(0)

    # Create a CSV writer
    with open(output_file, 'w', newline='', encoding='utf-8-sig') as csvfile:
        writer = csv.writer(csvfile)

        # Iterate over rows in the sheet
        for row_idx in range(sheet.nrows):
            row = sheet.row_values(row_idx)

            # Convert all values to strings, preserving trailing zeros
            row = [str(cell) for cell in row]
            writer.writerow(row)

xls_to_csv_with_zeros('input.xls', 'output.csv')

Exemple of my excel data : https://i.stack.imgur.com/ne9KX.png

What do I have to change to preserve my trailing zeros?
0

There are 0 best solutions below