Reputation: 21
I am currently converting a file from csv to xlsx. The problem is that the data is default converted all to strings. How can I convert the numbers (typically shown as +1.50000000000E+009 or " +1.50000000000E+009" (leading space) from string to number representations. I've tried typecasting and general workarounds but nothing works.
The "IF" statement is because the csv file has a header.
def csv_to_excel(csv_path, delimiter, delimiter_txt, excel_path, excel_title):
csv_file = open(csv_path, 'r')
csv.register_dialect(delimiter_txt, delimiter=delimiter)
reader = csv.reader(csv_file, dialect=delimiter_txt)
wb = Workbook()
ws = wb.worksheets[0]
ws.title = excel_title
for row_index, row in enumerate(reader):
for column_index, cell in enumerate(row):
column_letter = get_column_letter((column_index + 1))
if row_index > 3:
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = float(cell)
else:
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell
print(cell)
print(type(cell))
wb.save(filename = excel_path)
csv_file.close()
csv_to_excel('file.csv',',','comma','file.xlsx','data')
Thanks! Any help would be great!
Upvotes: 2
Views: 2588
Reputation: 3525
You should use float()
:
float("+1.50000000000E+009")
you can also use eval()
, however this could be potentially dangerous if you do not know for certain the type of input you'll be passing as a parameter.
eval("+1.50000000000E+009")
Both return 1500000000.0
Upvotes: 0
Reputation: 649
You can accomplish this using float()
.
>>> float("+1.50000000000E+009")
>>> 1500000000.0
Upvotes: 3