[Perspective] Read CSV with Comma as a Decimal Separator for Floats

I’m trying to correctly import some data from a CSV file with has numbers with commas as decimal separators. At the moment this is my code, but I’m trying to understand how to use locale to achieve my goal and correctly convert commas to dots. Any hints?

	import csv
	from StringIO import StringIO
	import locale
	reader = csv.reader(StringIO(event.file.getString("UTF-8")), delimiter=";")
	header = reader.next()
	self.view.custom.table.data = system.dataset.toDataSet(header, list(reader))

A CSV row is formatted like this:


I’ve solved this using:

reader = csv.reader(StringIO(event.file.getString("UTF-8")), delimiter=";")
l = []

for row in reader:
	item = []
	for column in row: item.append(column.replace(',', '.'))

self.view.custom.table.data = system.dataset.toDataSet(header, l)

Just want to point out that you’re asking for issues with this code:

  1. Never use built-in types for variable names
  2. At least in the script you have shown, list isn’t defined.

Something like this is better:

reader = csv.reader(StringIO(event.file.getString("UTF-8")),delimiter=";")

convertedData =[[column.replace(',','.') for column in row] for row in reader]
self.view.custom.table.data = system.dataset.toDataSet(header,convertedData)
1 Like